异步编程(进阶)


一:异步编程任务终止

public readonly struct CancellationToken 用于获取提前终止的信号。

一般通过 CancellationTokenSource来创建CancellationToken 

来看取消请求的例子:

using System.Text;
using System.Threading.Tasks;

CancellationTokenSource tcs=new CancellationTokenSource();
tcs.CancelAfter(TimeSpan.FromSeconds(5)); 
await Print(tcs.Token);

 async Task Print(CancellationToken cancellationToken)
{
    for (int i = 0; i < 10; i++)
    {
        await Task.Delay(1000);
        Console.WriteLine(i);
        if (cancellationToken.IsCancellationRequested)
        {
            Console.WriteLine("IsCancellationRequested...");
            break;
        }
    } 

}

输出

 线程取消报异常:

using System.Text;
using System.Threading.Tasks;

CancellationTokenSource tcs=new CancellationTokenSource();
tcs.CancelAfter(TimeSpan.FromSeconds(5));
await Print(tcs.Token);

async Task Print(CancellationToken cancellationToken)
{
for (int i = 0; i < 10; i++)
{
await Task.Delay(1000);
Console.WriteLine(i);
//if (cancellationToken.IsCancellationRequested)
//{
// Console.WriteLine("IsCancellationRequested...");
// break;
//}
cancellationToken.ThrowIfCancellationRequested();
}

Task.WhenAll / Task.WhenAny

 Task.WhenAll 

IEnumerablestring>> tasks = new[] { GetStr1(), GetStr2(), GetStr3() };

string[] strs= await Task.WhenAll(GetStr1(),GetStr2(),GetStr3());//==>//Task.WhenAll(tasks);

foreach (var item in strs)
{
    Console.WriteLine(item);
}

Task<string> GetStr1() => Task.FromResult("GetStr1");
Task<string> GetStr2() => Task.FromResult("GetStr2");
Task<string> GetStr3() => Task.FromResult("GetStr3");

 Task.WhenAny

var strs = await Task.WhenAny(GetStr1(), GetStr2(), GetStr3());//==>//Task.WhenAll(tasks);

if (strs.IsCompleted)
{
Console.WriteLine(strs.Result);
}


Task<string> GetStr1() => Task.FromResult("GetStr1");
Task<string> GetStr2() => Task.FromResult("GetStr2");
Task<string> GetStr3() => Task.FromResult("GetStr3");