TaskFactory

Provides support for creating and scheduling Task objects.

public class TaskFactory

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.

using System;
using System.IO;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task[] tasks = new Task[2];
      String[] files = null;
      String[] dirs = null;
      String docsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

      tasks[0] = Task.Factory.StartNew( () => files = Directory.GetFiles(docsDirectory));
      tasks[1] = Task.Factory.StartNew( () => dirs = Directory.GetDirectories(docsDirectory));

      Task.Factory.ContinueWhenAll(tasks, completedTasks => {
                                             Console.WriteLine("{0} contains: ", docsDirectory);
                                             Console.WriteLine("   {0} subdirectories", dirs.Length);
                                             Console.WriteLine("   {0} files", files.Length);
                                          } );
   }
}
// The example displays output like the following:
//       C:\Users\<username>\Documents contains:
//          24 subdirectories
//          16 files

Let's take a look at the following piece of code:

static void Main(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 = new Task(() => DoSomethingImportantWork(2, 3000));
    t2.Start();

    var t3 = new Task(() => DoSomethingImportantWork(3, 1000));
    t3.Start();

    Console.WriteLine("Press any key to quit");
    Console.ReadLine();
}

static void DoSomethingImportantWork(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

Last updated