Untiy中 Task 与多线程

结论:在Unity 中使用 Task 作为返回值并不会开启新的线程,调用方为主线程;如果是自己创建了Task 对象 即:new Task()则会新开辟一条线层进行处理。

测试场景1:  使用两个异步函数进行修改同一个变量,同时在异步函数之后进行 Main Thread 的 Id ,代码如下

using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using UnityFx.Async;

public class TestAsync2 : MonoBehaviour
{
    private int TestLog;
    private int Len = 5;
    private void Start()
    {
        Task t1 = Modify1();//主线程中执行,遇到 await 即可转交执行权
        Task t2 = Modify2();//主线程中执行,遇到 await 即可转交执行权
        Debug.LogError("Main Thread >>> " + System.Threading.Thread.CurrentThread.ManagedThreadId);
    }
  
    private async Task Modify1() {
       for(int i=0; i< Len; i++)
        {
            TestLog = i; await Task.Delay(1);
        }
        
        Debug.Log("t1 thread id >>> " + System.Threading.Thread.CurrentThread.ManagedThreadId);
    }

    private async Task Modify2()
    {
        for (int i = Len; i < 2*Len; i++)
        {
            TestLog = i; await Task.Delay(20);
        }
        Debug.Log("t2 thread id >>> " + System.Threading.Thread.CurrentThread.ManagedThreadId);
    }
    
    private void Update()
    {
        if (TestLog >= 2 * Len)
        {
            Debug.LogError(TestLog);
        } else if (TestLog >= Len) {
            Debug.LogWarning(TestLog);
        }
        else
        {
            Debug.Log(TestLog);
        }
    }

}

结果:MainThread -->t1/t2 

执行流程如下图,t1 遇到了await 则将控制权交还回去,立即执行t2 然后也遇到了await 将控制权交给了主线程中,这个时候t1 和 t2 还在执行中,同时在修改一个变量TestLog,具体每一帧执行了多少次t1, t2 是无法确定的,同时无法确定t1 和 t2 执行完毕后什么时候回到主线程中,t1 和 t2 不是在两个独立的线层中执行的,依然是
在主线程之中 

测试场景2: 使用new task 进行创建任务进行执行,通过Task 的 WaitAny 进行控制线程的执行流程,代码如下

using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using UnityFx.Async;

public class TestAsync : MonoBehaviour
{
    private int Len = 100;
    private int TestLog;
    private void Start()
    {
        Task t11 = CreateTask("t11", 1); //创建会出现新的线程
        Task t12 = CreateTask("t12", 10); //创建会出现新的线程
        Task.WaitAny(t11, t12);
        Debug.LogError("Main Thread >>> " + System.Threading.Thread.CurrentThread.ManagedThreadId);
    }

    private Task CreateTask(string tag, int sleepTime) {
        Task t = new Task(() => {
            for (int i = 0; i < Len; i++)
            {
                TestLog = i; Thread.Sleep(sleepTime);
            }
            Debug.LogError(tag + "thread id >>> " + System.Threading.Thread.CurrentThread.ManagedThreadId);
        });
        t.Start();
        return t;
    }
}

执行结果  t11 thread -- main thread -- t12 thread

t11 在执行完毕后,由于给线程管理器下达的命令是任何一个执行完毕就把执行权交回来,所以立即执行了Main Thread >>> 1, 最后执行了t12 

 

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Unity 3D使用多线程可以通过使用C#提供的System.Threading命名空间来实现。在Unity多线程主要用于处理一些耗时的操作,以避免阻塞主线程而导致应用程序卡顿。 要在Unity 3D使用多线程,可以按照以下步骤进行操作: 1. 导入System.Threading命名空间:在需要使用多线程的脚本,首先需要在文件开头导入System.Threading命名空间。 2. 创建并启动新线程:使用Thread类可以创建一个新的线程。例如,可以使用Thread.Start()方法来启动线程,如`Thread thread = new Thread(MethodName); thread.Start();`。其,MethodName是一个自定义的方法,用于在线程执行。 3. 定义线程执行的方法:在上一步提到的MethodName,我们可以编写实际执行的代码。 4. 多线程安全问题:在多线程环境下,多个线程可能同时访问或修改同一个数据,需要注意线程安全问题。为了避免多线程竞态条件,可以使用锁机制(lock)对共享资源进行保护。 5. 线程间通信:在多线程,有时需要将执行结果或其他信息传递给主线程。可以使用Unity提供的ThreadedJob类来实现线程间通信。ThreadedJob类可以将数据从子线程传递到Unity主线程,并提供回调方法来处理数据。 需要注意的是,在Unity多线程主要用于处理非图形相关的操作,比如网络请求、数据计算等。在许多情况下,通过合理的异步操作也可以避免使用多线程,以简化代码逻辑和维护。另外,由于Unity3D是单线程渲染的,所以在多线程直接修改Unity对象可能会导致一些潜在的问题,需要谨慎使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值