三种方式都使用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
{
Co