SoFunction
Updated on 2025-03-06

TaskFactory implementation in C#

In C#, TaskFactory is a class used to create asynchronous tasks. It provides a convenient way to create Task objects that represent operations that can be performed asynchronously. The TaskFactory class is located under the namespace.

To use TaskFactory, you need to import the corresponding namespace:

using ;

The TaskFactory class provides several static methods for creating different types of asynchronous tasks. Here are some common methods of TaskFactory:

  • StartNew(): Create a new asynchronous task and start execution immediately. This is one of the most commonly used methods.
  • FromAsync(): Creates an asynchronous task that will be derived from an existing asynchronous operation.
  • ContinueWith(): Creates an asynchronous task that executes immediately after the specified task is completed.

Here is an example using TaskFactory that demonstrates how to create and run asynchronous tasks:

using System;  
using ;  
  
class Program  
{  
    static void Main(string[] args)  
    {  
        // Create asynchronous tasks        Task<int> asyncTask = <int>(() =>  
        {  
            // Simulation time-consuming operation            (2000);  
            return 42; // Return result        });  
  
        // Callback function after registration task is completed        (t =>  
        {  
            ("Async task is completed, and the result is:" + );  
        });  
  
        // Wait for user input to pause program execution before task completion        ();  
    }  
}

In the example above, we create an asynchronous task using the StartNew method of TaskFactory. The task will sleep for 2 seconds and then return 42 as the result. We then register a callback function using the ContinueWith method, which is called after the asynchronous task is completed and outputs the result of the task. Finally, we use() to wait for user input to pause program execution before the task is completed.

(() => { method; }, );

In the TaskCreationOptions enumeration of C#, there are the following types:

  • Normal: This is the default option, indicating that tasks should be created and executed in a normal way.
  • AttachedToParent: This option means that the task should be attached to the parent task() or suspended task() as a child task.
  • LongRunning: This option means that a task may run for a long time and should be considered a long-running task, even if its code block is asynchronous.
  • PreemptiveSTA: This option means that the task will exclusively occupy the STA thread and prevent any other tasks from running on that thread.
  • DuplicateDetection: This option means that the task should enable duplicate detection. If the task is canceled by another task during execution, the task will not be restarted.
  • DelayCreation: This option indicates delayed execution when creating a task. This allows tasks to be created and scheduled if needed, rather than created and scheduled immediately.
  • Complete: This option means that the task can be completed after completion. This allows waiting for the task to be completed by using or TaskCompletionSource.
    These different types of TaskCreationOptions can affect the creation, execution and completion of tasks. Choosing the appropriate type according to different needs can better manage the execution of asynchronous tasks.

This is all about this article about TaskFactory implementation in C#. For more related C# TaskFactory content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!