被多数异步方法都青睐的参数:请求限时-CancellationToken
当请求发出去后,即使客户端关闭但服务器会继续做处理,没必要,所以CancellationToken来取消处理。
可以使用在请求超时、用户取消请求、网页关闭、断网等场景
而且很多异步方法都支持CancellationToken参数用于提前获取终止执行的信号
1、IsCancellationRequested属性:是否取消
static async Task Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
//指定5秒后IsCancellationRequested为true
cts.CancelAfter(5000);
CancellationToken cancellationToken = cts.Token;
using (HttpClient client = new HttpClient())
{
for (int i = 0; i < 50; i++)
{
string html = await client.GetStringAsync("https://www.baidu.com");
//判断
if (cancellationToken.IsCancellationRequested)
{
Console.WriteLine("请求被取消");
break;
}
Console.WriteLine(html);
}
}
}
5秒后真被取消了
2、ThrowIfCancellationRequested():如果任务被取消,执行到这句话就抛异常
static async Task Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
//指定5秒后IsCancellationRequested为true
cts.CancelAfter(5000);
CancellationToken cancellationToken = cts.Token;
using (HttpClient client = new HttpClient())
{
for (int i = 0; i < 50; i++)
{
var html = await client.GetStringAsync("https://www.baidu.com");
//如果任务被取消,执行到这句话就抛异常
cancellationToken.ThrowIfCancellationRequested();
Console.WriteLine(html);
}
}
}
真就异常了
3、多数异步方法都支持CancellationToken参数
static async Task Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
//指定5秒后IsCancellationRequested为true
cts.CancelAfter(5000);
CancellationToken cancellationToken = cts.Token;
using (HttpClient client = new HttpClient())
{
for (int i = 0; i < 50; i++)
{
//作为参数传递,则会自动抛出异常
var resp = await client.GetAsync("https://www.baidu.com", cancellationToken);
var html = resp.Content.ReadAsStringAsync();
Console.WriteLine(html);
}
}
}
相当于ThrowIfCancellationRequested()的异常,但是这种更推荐,因为使用ThrowIfCancellationRequested()时,当取消的时间正好在await的时间之内,则本次await不会及时被阻止,而作为参数传递是准时阻止的。
4、也可以自定义取消的触发条件
CancellationTokenSource cts = new CancellationTokenSource();
//cts.CancelAfter(5000);
CancellationToken cancellationToken = cts.Token;
async Task A()
{
await client.GetAsync("https://www.baidu.com", cancellationToken);
}
//触发了B方法则取消A方法中的await操作
void B(取消的条件,cts)
{
cts.Cancel()
}
标签:cancellationToken,await,限时,请求,CancellationToken,cts,CancellationTokenSource,new
From: https://www.cnblogs.com/long-live/p/c.html