结论:在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