Unity 多线程编程笔记 _Task详解

Task技术进行了大量的封装,在ThreadPool的基础上进行开发,如果使用.net4.0以上的版本开发,建议使用这门技术。

  1. Task支持多种创建模式
void Start()
    {
        Debug.Log("主线程ID"+Thread.CurrentThread.ManagedThreadId);

        //new关键字
        Task t1 = new Task(() =>
        {
            Debug.Log("使用New关键字创建的线程ID:" + Thread.CurrentThread.ManagedThreadId);
        });

        //静态方法
        Task.Run(() => {
            Debug.Log("使用静态方法创建的线程ID:" + Thread.CurrentThread.ManagedThreadId);
        });

        //工厂  
        //使用线程池
        Task.Factory.StartNew(() =>{
            Debug.Log("使用工厂创建的线程ID:" + Thread.CurrentThread.ManagedThreadId);
        });
        //单独创建线程
        Task.Factory.StartNew(() => {
            Debug.Log("使用工厂创建的线程ID:" + Thread.CurrentThread.ManagedThreadId);
        }, TaskCreationOptions.LongRunning);
    }

Unity 多线程编程笔记 _Task详解_第1张图片

  1. Task支持完成任务后可以添加回调
    void Start()
    {
        Task t1 = new Task(() =>
          {
              for (int i = 0; i < 3; i++)
              {
                  Debug.Log(i);
              }
          });
        t1.Start();
        t1.ContinueWith((t2) =>
        {
            Debug.Log("t1执行完毕");
        });

    }

Unity 多线程编程笔记 _Task详解_第2张图片
3. Task 支持带返回值

    void Start()
    {
        Task<int> t1 = new Task<int>(WithResult);
        t1.Start();
        t1.Wait(); //等待任务完成
        Debug.Log(t1.Result);

    }
    public  int WithResult()
    {
        return 16;
    }

在这里插入图片描述
4.支持任务嵌套

 void Start()
    {
        //父任务中开启多个子任务,所有子任务执行完毕后父任务结束执行
        Task<string> ParentTask = new Task<string>(() =>
        {
            Debug.Log("Woring");
            Task<string> son01 = new Task<string>(() =>
             {
                 return "子任务01";
             }, TaskCreationOptions.AttachedToParent);
            son01.Start();
            Task<string> son02 = new Task<string>(() =>
            {
                return "子任务02";
            },TaskCreationOptions.AttachedToParent);
            son02.Start();

            return son01.Result +"*****"+ son02.Result;
        });
        
        ParentTask.Start();
        ParentTask.Wait();
        Debug.Log(ParentTask.Result);
    }

Unity 多线程编程笔记 _Task详解_第3张图片
5. 支持取消

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

public class TestTask : MonoBehaviour
{
    void Start()
    {

        var cts = new CancellationTokenSource();
        var longTask = new Task<int>(() => TaskMethod("Task 1", 10, cts.Token), cts.Token);
        Debug.Log(longTask.Status);
        cts.Cancel();
        Debug.Log(longTask.Status);
        Debug.Log("First task has been cancelled before execution");


        cts = new CancellationTokenSource();
        longTask = new Task<int>(() => TaskMethod("Task 2", 10, cts.Token), cts.Token);
        longTask.Start();
        for (int i = 0; i < 5; i++)
        {
            Thread.Sleep(TimeSpan.FromSeconds(0.5));
            Debug.Log(longTask.Status);
        }
        cts.Cancel();
        for (int i = 0; i < 5; i++)
        {
            Thread.Sleep(TimeSpan.FromSeconds(0.5));
            Debug.Log(longTask.Status);
        }
        Debug.LogFormat("A task has been completed with result {0}.", longTask.Result);
     


    }
    private static int TaskMethod(string name, int seconds, CancellationToken token)
    {
        Debug.LogFormat("Task {0} is running on a thread id {1},Is thread pool thread: {2}",
                           name, Thread.CurrentThread.ManagedThreadId,
                           Thread.CurrentThread.IsThreadPoolThread);
        for (int i = 0; i < seconds; i++)
        {
            Thread.Sleep(TimeSpan.FromSeconds(1));
            if (token.IsCancellationRequested)
            {
                return -1;
            }
        }
        return 42 * seconds;
    }

}

Unity 多线程编程笔记 _Task详解_第4张图片

你可能感兴趣的:(Unity小案例)