小编Sat*_*Sat的帖子

使用 IsCancellationRequested 属性?

什么是使用CancellationTokenIsCancellationRequested财产?考虑下面的代码

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");
}
Run Code Online (Sandbox Code Playgroud)

我发现在极少数情况下if块内的代码不运行。如果是这样,轮询查看是否请求取消有什么用?

c# parallel-processing task-parallel-library

4
推荐指数
1
解决办法
1万
查看次数