TaskFactory<TResult> Class
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
-
TaskFactory<TResult>()
Initializes a new instance of the TaskFactory<TResult> class with default settings.
Constructor -
TaskFactory<TResult>(CancellationTokenCancellationTokenSource)
Initializes a new instance of the TaskFactory<TResult> class with the specified cancellation token source.
Constructor -
TaskFactory<TResult>(TaskScheduler)
Initializes a new instance of the TaskFactory<TResult> class with the specified task scheduler.
Constructor
Properties
-
CancellationToken CancellationToken { get; }
Gets the default cancellation token that will be used by tasks created by this TaskFactory<TResult> instance.
Property -
TaskScheduler Scheduler { get; }
Gets the default task scheduler that will be used by tasks created by this TaskFactory<TResult> instance.
Property
Methods
-
Task<TResult> StartNew(Func<TResult> function)
Creates and starts a new task that will run asynchronously using the state associated with this instance.
Method -
Task<TResult> StartNew(Func<Task<TResult>> function)
Creates and starts a new task that will run asynchronously.
Method -
Task<TResult> StartNew<TState>(Func<TState, TResult> function, TState state)
Creates and starts a new task that will run asynchronously using the specified state.
Method
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}");
}
}