C# 异步 取消终止
static async Task Main(string[] args){
CancellationTokenSource cts=new CancellationTokenSource();
cts.CancelAfter(5000);//5秒之后取消操作
CancellationToken cToken=cts.Token;
await DownLoad2Async("https://www.baidu.com",200,cToken);
}
关键类型:CancellationToken
static async Task Download2Async(string url,int n,CancellationToken cancellationToken){
using(HttpClient client=new HttpClient())
for(int ii=0;i<n;i++)
stirng html=await client.GetStringAsync(url);
Console.WriteLine($"{dateTime.Now}:{html}");
//方式1
if(cancellationToken.IsCancellationRequested){
Console.WriteLine("请求被取消”)
//方式2
cancellationToken.ThrowIfCancellationRequested();//这种方式会抛出一个异常,说明操作被取消了。
}
}