1 概述
cts = new CancellationTokenSource();
cts.Token.Register(()=>Console.WriteLine(" task cancelled"));
cts.Token.Register(()=>Console.WriteLine(" task cancelled"));
CancellationToken token = cts.Token;
if (token.IsCancellationRequested) {
2. 代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApp8
{
class Program
{
static CancellationTokenSource cts;
static void Main(string[] args)
{
Console.WriteLine("hello word");
CancelTask();
Console.ReadKey();
}
static void CancelTask() {
cts = new CancellationTokenSource();
cts.Token.Register(()=>Console.WriteLine(" task cancelled"));
cts.CancelAfter(500);
Task t1 = Task.Run(fun, cts.Token);
try
{
t1.Wait();
}
catch (AggregateException ex) {
Console.WriteLine($"exception {ex.Message}");
}
}
static void fun() {
Console.WriteLine("in taak");
for (int i = 0; i < 20; i++) {
Task.Delay(100).Wait();
CancellationToken token = cts.Token;
if (token.IsCancellationRequested) {
Console.WriteLine("cancelling waa requested");
//token.ThrowIfCancellationRequested();
break;
}
Console.WriteLine("in loop {0}",i);
}
Console.WriteLine("task finished without cancellation");
}
}
}
3 运行效果
4.代码分析