SoFunction
Updated on 2025-03-03

Detailed explanation of the usage of Task task class in C#

Preface

The Task class is an important tool for multi-threading and asynchronous operations on the .NET platform. It provides simple and powerful API support, allowing developers to use system resources more efficiently and implement complex parallel and asynchronous operations. Whether in I/O-intensive operations or CPU-intensive tasks, the Task class can provide strong support to developers.

Meet Task

Namespace:

Class name: Task

Task, as the name suggests, means task

Task is an improvement based on thread pool. It has the advantages of thread pools and solves the disadvantage that it is difficult to control using thread pools.

It encapsulates threads based on the advantages of thread pools, which allows us to carry out multi-threading development more conveniently and efficiently.

Simple understanding:

The essence of Task is to encapsulate thread Thread. Its creation follows the advantages of thread pools and allows us to control threads more conveniently.

A Task object is a thread.

Three ways to create a Task without a return value

The first method

Pass in the delegate function through new Task object and start

        Task t1 = new Task(() =>
        {
            int i = 0;
            while (isRuning)
            {
                print("Method One:" + i);
                ++i;
                (1000);
            }
        });
        ();

The second way

Passing in delegate function through Run static method in Task

        Task t2 = (() =>
        {
            int i = 0;
            while (isRuning)
            {
                print("Method 2:" + i);
                ++i;
                (1000);
            }
        });

The third way

Pass the delegate function through the StartNew static method

Task t3 = (() =>
{
    int i = 0;
    while (isRuning)
    {
        print("Method Three:" + i);
        ++i;
        (1000);
    }
});

Returns a Task with a return value

The first method

Break into the delegate function by new Task object and start

t1 = new Task<int>(() =>
{
    int i = 0;
    while (isRuning)
    {
        print("Method One:" + i);
        ++i;
        (1000);
    }
    return 1;
});
();

The second way

Passing in delegate function through Run static method in Task

t2 = <string>(() =>
{
    int i = 0;
    while (isRuning)
    {
        print("Method 2:" + i);
        ++i;
        (1000);
    }
    return "1231";
});

The third way

Pass the delegate function through the StartNew static method

t3 = <float>(() =>
{
    int i = 0;
    while (isRuning)
    {
        print("Method Three:" + i);
        ++i;
        (1000);
    }
    return 4.5f;
});

Get the return value

Notice:

Result blocks the thread when getting the result

That is, if the task is not executed

Will wait for the task to be executed and get the Result

Then execute the subsequent code, that is, when executing this code, since our Task is a dead loop.

So the main thread will be stuck

Synchronous execution of Task

The examples we gave before were all performed asynchronously through multi-threading

If you want Task to be executed synchronously

Just call the RunSynchronously method in the Task object

Note: The new Task object needs to be used, because Run and StartNew will start when created.

        Task t = new Task(() =>
        {
            (1000);
            print("This is a sentence");
        });
        //();
        ();
        print("Main thread execution");

Not Start but RunSynchronously

How to block threads in Task

Method: Wait for the task to be executed before executing the following content

 Task t1 = (() =>
 {
     for (int i = 0; i < 5; i++)
     {
         print("t1:" + i);
     }
 });

 Task t2 = (() =>
 {
     for (int i = 0; i < 20; i++)
     {
         print("t2:" + i);
     }
 });
​​​​​​​//();

Static method: continue to execute any task in the incoming task after the end

(t1, t2);

Static method: All tasks in the task list continue to execute after the execution is completed.

(t1, t2);

After the task is completed, continue other tasks (task continuation)

Static method + ContinueWith method: Execute a certain task after the incoming task is completed

using ;
using ;
using UnityEngine;
 
public class Test : MonoBehaviour
{
    Task t1,t2;
 
    bool isRuning =true;
    void Start()
    {
        (t1, t2).ContinueWith((t) =&gt;
        {
            print("A new mission has begun");
            int i = 0;
            while (isRuning)
            {
                print(i);
                ++i;
                (1000);
            }
        });
 
        (new Task[] { t1, t2 }, (t) =&gt;
        {
            print("A new mission has begun");
            int i = 0;
            while (isRuning)
            {
                print(i);
                ++i;
                (1000);
            }
        });
 
    }
    private void OnDestroy()
    {
        isRuning = false;
    }
}

Static method + ContinueWith method: Only one of the incoming tasks will be executed before executing them.

using ;
using ;
using UnityEngine;
 
public class Test : MonoBehaviour
{
    Task t1,t2;
 
    bool isRuning =true;
    void Start()
    {
        (t1, t2).ContinueWith((t) =&gt;
        {
            print("A new mission has begun");
            int i = 0;
            while (isRuning)
            {
                print(i);
                ++i;
                (1000);
            }
        });
 
        (new Task[] { t1, t2 }, (t) =&gt;
        {
            print("A new mission has begun");
            int i = 0;
            while (isRuning)
            {
                print(i);
                ++i;
                (1000);
            }
        });
 
    }
    private void OnDestroy()
    {
        isRuning = false;
    }
}

Cancel Task execution

Method 1: Control the end of the dead loop in the thread by adding the bool tag

Method 2: CancellationTokenSource to control

CancellationTokenSource object can achieve delayed cancellation, cancel callback and other functions

using ;
using ;
using UnityEngine;
 
public class Test : MonoBehaviour
{
    Task t1,t2;
 
    CancellationTokenSource c;
    void Start()
    {
        c = new CancellationTokenSource();
        //Delay cancellation        (5000);
        //Cancel callback        (() =&gt;
        {
            print("The mission was cancelled");
        });
        (() =&gt;
        {
            int i = 0;
            while (!)
            {
                print("Time:" + i);
                ++i;
                (1000);
            }
        });
 
    }
    private void OnDestroy()
    {
        ();
    }
}

Summarize

Classes are Thread-based encapsulation

The class can have a return value, but Thread does not return value

The class can perform subsequent operations, but Thread does not have this function

Cancel tasks more conveniently, Thread is relatively simple

With the advantages of ThreadPool thread pool, it saves performance

This is the end of this article about the detailed explanation of the usage of Task task classes in C#. For more related content of C# Task task classes, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!