Provides support for creating and scheduling Task objects.
publicclassTaskFactory
Examples
The following example uses the static Factory property to make two calls to the TaskFactory.StartNew method. The first populates an array with the names of files in the user's MyDocuments directory, while the second populates an array with the names of subdirectories of the user's MyDocuments directory. It then calls the TaskFactory.ContinueWhenAll(Task[], Action<Task[]>) method, which displays information about the number of files and directories in the two arrays after the first two tasks have completed execution.
staticvoidMain(string[] args){ /// This guy will be initialized immediately /// So we do not actually need the .Start() to initialize the Task /// It will do it automatically.var t1 =Task.Factory.StartNew(() =>DoSomethingImportantWork(1,1500));var t2 =newTask(() =>DoSomethingImportantWork(2,3000));t2.Start();var t3 =newTask(() =>DoSomethingImportantWork(3,1000));t3.Start();Console.WriteLine("Press any key to quit");Console.ReadLine();}staticvoidDoSomethingImportantWork(int id,int sleepTime){Console.WriteLine("Task {0} is beginning", id);Thread.Sleep(sleepTime);Console.WriteLine("Task {0} has completed", id);}
ContinueWith(Action<Task>)
Creates a continuation that executes asynchronously when the target Task completes.
/// This guy will be initialized immediately/// So we do not actually need the .Start() to initialize the Task/// It will do it automatically.var t1 =Task.Factory.StartNew(() =>DoSomethingImportantWork(1,1500)) .ContinueWith((prevTask) =>DoSomeOtherImportantWork(1,1000));
// Press any key to quit// Task 2 is beginning// Task 1 is beginning// Task 3 is beginning// Task 3 has completed// Task 1 has completed// Task 1 is beginning ===> here is our ContinueWith// Task 1 has completed// Task 2 has completed