C# async&await+Task

async&await

异步方法,使用起来更方便;(untiy自带的startcoroutine和invoke也方便,但必须继承MonoBehaviour,使用回调的方式实现异步);

await会开启新的线程;

async关键字的函数中必须有await关键字使用;

返回: void,Task,Task

可以有参数,参数不能带out和ref;

有些平台不支持多线程,比如webgl...;

//无返回值
private async void Function2Async()
{
    await Task.Delay(1000);
}

//有返回值
private async Task<string> FunctionAsync()
{
    var res = await Task.Run(() => { Debug.Log("aaa"); return "kkk"; });
    return res;
}

Task

Task在多线程程序使用;

Task在线程池上进行了优化,提供了更多好用的api;

//无法返回值,调用方式
var t1 = new Task(() => { Debug.Log("BB"); });
t1.Start();
Task.WaitAll(t1);

var t2 = Task.Run(() => { Debug.Log("BB"); });
t2.Wait();

var t3 = Task.Factory.StartNew(() => { Debug.Log("BB"); });
Task.WaitAll(t3);

//有返回值
Task<int> task = new Task<int>(() => { return 1; });
task.Start();
int result = task.Result;

//5,6并行,4,7串行
var t4 = new Task(() => { Debug.Log("BB"); });
t4.Start();

var t5 = t4.ContinueWith(t => { Debug.Log("cc"); });
var t6 = t4.ContinueWith(t => { Debug.Log("dd"); });

Task.WaitAll(t5, t6);

var t7 = Task.Factory.StartNew(() => { Debug.Log("ee"); });
t7.Wait();

//子任务TaskCreationOptions.AttachedToParent
Task<string[]> t8 = new Task<string[]>(() =>{
    var a = new Task<string>(() => { return "bbb"; }, TaskCreationOptions.AttachedToParent);
    a.Start();

    var b = new Task<string>(() => { return"ccc"; }, TaskCreationOptions.AttachedToParent);
    b.Start();

    return new string[] {a.Result, b.Result};   
});

t8.ContinueWith(t => {
    Debug.Log(t.Result[0]+t.Result[1]);
});

//取消任务CancellationTokenSource
var cts = new CancellationTokenSource();
var t9 = new Task<int>(() => { return 1; }, cts.Token);
cts.Cancel();

posted @ 2022-05-05 16:55  小紫苏  阅读(523)  评论(0编辑  收藏  举报