TaskFactory<TResult> Class

Namespace: System.Threading.Tasks
Assembly: System.Private.CoreLib

Represents the mechanism by which tasks are created and scheduled.

The TaskFactory<TResult> class is a generic class that provides a factory for creating and scheduling tasks. It allows for fine-grained control over task creation, including specifying options for task execution, cancellation tokens, and task continuations.

Constructors

Properties

Methods

Example

The following example demonstrates how to use TaskFactory<TResult> to create and run tasks:


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

public class Example
{
    public static void Main(string[] args)
    {
        // Create a TaskFactory for tasks returning integers
        TaskFactory factory = new TaskFactory();

        // Start a new task to calculate a value
        Task task = factory.StartNew(() =>
        {
            Console.WriteLine("Task is running...");
            Thread.Sleep(1000); // Simulate work
            return 42;
        });

        // Wait for the task to complete and get the result
        int result = task.Result;
        Console.WriteLine($"Task completed with result: {result}");
    }
}