三种方式都使用CancellationToken,只是使用方式不同,有类似于采用全局标志位的方式
第一种 检测IsCancellationRequested方式
static void AsyncOperation1(CancellationToken token)
{
Console.WriteLine("starting the first task");
for (int i = 0; i < 5; i++)
{
//取消任务信号
if (token.IsCancellationRequested)
{
Console.WriteLine("the first task has been canceled.");
return;
}
Thread.Sleep(TimeSpan.FromSeconds(1));
}
Console.WriteLine("the first task has completed successfully");
}
第二种 抛出ThrowIfCancellationRequested方式
static void AsyncOperation2(CancellationToken token)
{
try
{
Console.WriteLine("starting the second task");
for (

本文详细介绍了在C#线程池中取消线程的三种方法:通过检测IsCancellationRequested、抛出ThrowIfCancellationRequested异常以及注册取消方法。每种方式都利用了CancellationToken,并且在实际应用中提供了类似全局标志位的取消机制。
最低0.47元/天 解锁文章
1163

被折叠的 条评论
为什么被折叠?



