Task<TResult>.Factory Property

Definition

Gets a factory method for creating and configuring Task<TResult> instances.

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

Property Value

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

Remarks

This property returns a default instance of the TaskFactory<TResult> class that is identical to the one created by calling the parameterless TaskFactory<TResult>.TaskFactory<TResult>() 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<TResult>.StartNew method.

Note

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

The following example uses the static Factory property to make three calls to the TaskFactory<TResult>.StartNew method. The first starts a Task<Int32> object, which executes a lambda expression that returns 1. The second starts a Task<Test> object, which executes a lambda expression that instantiates a new Test instance. The third starts a Task<String[]> object, which enumerates the files in the C:\Users\Public\Pictures\Sample Pictures\ directory. (Note that successful execution of the example requires that the directory exist and that it contain files.

C#
using System;
using System.Linq;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        // Return a value type with a lambda expression
        Task<int> task1 = Task<int>.Factory.StartNew(() => 1);
        int i = task1.Result;

        // Return a named reference type with a multi-line statement lambda.
        Task<Test> task2 = Task<Test>.Factory.StartNew(() =>
        {
            string s = ".NET";
            double d = 4.0;
            return new Test { Name = s, Number = d };
        });
        Test test = task2.Result;

        // Return an array produced by a PLINQ query
        Task<string[]> task3 = Task<string[]>.Factory.StartNew(() =>
        {
            string path = @"C:\Users\Public\Pictures\Sample Pictures\";
            string[] files = System.IO.Directory.GetFiles(path);

            var result = (from file in files.AsParallel()
                          let info = new System.IO.FileInfo(file)
                          where info.Extension == ".jpg"
                          select file).ToArray();

            return result;
        });

        foreach (var name in task3.Result)
            Console.WriteLine(name);
    }
    class Test
    {
        public string Name { get; set; }
        public double Number { get; set; }
    }
}

Applies to

Product Versions
.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, 10
.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