CancellationToken
的属性有什么用IsCancellationRequested
?考虑下面的代码
static void Main(string[] args)
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
Console.WriteLine("Press Enter to Start.\nAgain Press enter to finish.");
Console.ReadLine();
Task t = new Task(() =>
{
int i = 0;
while (true)
{
if (token.IsCancellationRequested)
{
Console.WriteLine("Task Cancel requested");
break;
}
Console.WriteLine(i++);
}
}, token);
t.Start();
// wait for input before exiting
Console.ReadLine();
tokenSource.Cancel();
if(t.Status==TaskStatus.Canceled)
Console.WriteLine("Task was cancelled");
else
Console.WriteLine("Task completed");
}
我发现在极少数情况下,if
块内的代码不会运行。如果是这样,轮询以查看是否请求取消有什么用?