浅谈C#中取消令牌CancellationTokenSource
[*]基础操作 CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.Token.Register(() =>
{
Console.WriteLine("取消了1111");
});
cancellationTokenSource.Token.Register(() =>
{
Console.WriteLine("取消了2222");
});
cancellationTokenSource.Cancel();取消了2222
取消了1111
[*]超时自动取消
[*]new CancellationTokenSource(3000);
[*]cancellationTokenSource.CancelAfter(3000);
[*]关联取消 CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationTokenSource cancellationTokenSource2 = new CancellationTokenSource();
cancellationTokenSource.Token.Register(() =>
{
Console.WriteLine("取消了1111");
});
cancellationTokenSource2.Token.Register(() =>
{
Console.WriteLine("取消了2222");
});
var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token,
cancellationTokenSource2.Token);
linkedTokenSource.Token.Register(() =>
{
Console.WriteLine("关联令牌被取消了");
});
//cancellationTokenSource.Cancel();
cancellationTokenSource2.Cancel();关联令牌被取消了
取消了2222令牌1和2的任意一个取消,关联令牌linkedTokenSource就会被取消。但是关联令牌linkedTokenSource取消,令牌1和2并不会取消。
[*]判断取消 CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.Token.Register(() =>
{
Console.WriteLine("取消了1111");
});
Task.Run(async () =>
{
while (!cancellationTokenSource.IsCancellationRequested)
{
Console.WriteLine("一直在执行...");
await Task.Delay(1000);
}
});
cancellationTokenSource.CancelAfter(3000);一直在执行...
一直在执行...
一直在执行...
取消了1111 CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
Task.Run(async () =>
{
try
{
while (true)
{
//如果操作被取消则直接抛出异常
cancellationTokenSource.Token.ThrowIfCancellationRequested();
Console.WriteLine("一直在执行...");
await Task.Delay(1000);
}
}
catch (OperationCanceledException ex)
{
Console.WriteLine("取消了!");
}
});
cancellationTokenSource.CancelAfter(3000);一直在执行...
一直在执行...
一直在执行...
取消了!使用ThrowIfCancellationRequested会抛出OperationCanceledException异常,需要自己捕获处理
来源:https://www.cnblogs.com/log9527blog/archive/2023/07/21/17571326.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页:
[1]