c# - 将 CancellationToken 传递给任务类构造函数有什么用?

标签 c# .net multithreading cancellation-token

这是一个示例代码,它创建了一个模拟长时间运行的进程的新任务。任务本身并没有太多内容,只是专注于取消功能。我正在使用取消 token 取消任务,代码对我来说工作正常。

CancellationTokenSource CTS = new CancellationTokenSource();

Task<Boolean> PTask = new Task<Boolean>(() => 
{
   while (true)
   {
       if (!CTS.Token.IsCancellationRequested)
       {
          Thread.Sleep(5000);
       }
       else { Console.WriteLine("Thread Cancelled");break; }
   }
   return true;

}, CTS.Token, TaskCreationOptions.None);

PTask.Start();
Console.WriteLine("Hit Enter to cancel the Secondary thread you have started");
Console.ReadLine();
CTS.Cancel();
System.Console.WriteLine(PTask.Result);

但我无法理解的一件事是传递给 Task 构造函数的 token 参数 (CTS.Token)。传递参数的实际用途是什么,即使不将 token 传递给构造函数,我实际上也可以取消任务。

下面是一个稍微修改过的版本,可以在没有 token 参数的情况下使用。

CancellationTokenSource CTS = new CancellationTokenSource();
Task<Boolean> PTask = new Task<Boolean>(() => 
{
   while (true)
   {
       if (!CTS.Token.IsCancellationRequested)
       {
           Thread.Sleep(5000);
       }
       else
       {
           Console.WriteLine("Thread Cancelled");
           break;
       }
};

最佳答案

更新: 以下msdn问题描述原因:

Passing a token into StartNew associates the token with the Task. This has two primary benefits:

  1. If the token has cancellation requested prior to the Task starting to execute, the Task won't execute. Rather than transitioning to Running, it'll immediately transition to Canceled. This avoids the costs of running the task if it would just be canceled while running anyway.

  2. If the body of the task is also monitoring the cancellation token and throws an OperationCanceledException containing that token (which is what ThrowIfCancellationRequested does), then when the task sees that OCE, it checks whether the OCE's token matches the Task's token. If it does, that exception is viewed as an acknowledgement of cooperative cancellation and the Task transitions to the Canceled state (rather than the Faulted state).

关于c# - 将 CancellationToken 传递给任务类构造函数有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10848484/

相关文章:

Exchange 2013 上的 C# EWS Api : Get an attachment into a Stream

c# - 使用 .net sdk 在 Azure 数据工厂 V2 中重新运行事件

.net - Visual Studio : Cannot find the interop type that matches the embedded type 'DOMDocument' . 您是否缺少程序集引用?

.net - 设置默认样式键的方法之间的差异

java - 有效实现此 Java MouseListener 逻辑

java - 是否-XX :+UseSerialGC use main thread for GC

c++ - 定义线程函数时的 std::thread 表示法

c# - 退出工作流程?

c# - 如何捕获 CheckInvalidPathChars() 异常

c# - 抑制 Visual Studio 中所有项目的警告