Task.Factory Property

Definition

Provides access to factory methods for creating and configuring Task and Task<TResult> instances.

C#
public static System.Threading.Tasks.TaskFactory Factory { get; }

Property Value

A factory object that can create a variety of Task and Task<TResult> objects.

Remarks

This property returns a default instance of the TaskFactory class that is identical to the one created by calling the parameterless TaskFactory.TaskFactory() constructor. It has the following property values:

The most common use of this property is to create and start a new task in a single call to the TaskFactory.StartNew method.

Uwaga

Starting with the .NET Framework 4.5, the Task.Run method provides the easiest way to create a Task object with default configuration values.

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.

C#
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

Applies to

Produkt Wersje
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

See also