什么是使用过的CancellationToken到任务类的构造函数? [英] What is the use of passing CancellationToken to Task Class constructor?

查看:274
本文介绍了什么是使用过的CancellationToken到任务类的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是创建模拟长时间运行的process.There新任务的示例代码是没有什么太多的任务,这样的纯粹和专注于取消features.I正在使用取消标记取消任务和代码工作。对我罚款

  CancellationTokenSource CTS =新CancellationTokenSource(); 

任务<布尔> PTask =新任务<布尔>(()=>
{
,而(真)
{
如果(CTS.Token.IsCancellationRequested)
{$! b $ b Thread.sleep代码(5000);
}
其他{Console.WriteLine(线程已取消);打破;}
}
返回真;

},CTS.Token,TaskCreationOptions.None);

PTask.Start();
Console.WriteLine(按Enter键,取消您已启动辅助线程);
到Console.ReadLine();
CTS.Cancel();
的System.Console.WriteLine(PTask.Result);

}
}



但onething,我无法理解是被传递到任务Constructor.What令牌参数(CTS.Token)是实际使用传递参数,当我其实可以取消任务,即使没有传递令牌来构造的。



楼下是,没有令牌参数工作方式稍作修改的版本。

  CancellationTokenSource CTS =新CancellationTokenSource(); 
任务<布尔> PTask =新任务<布尔>(()=>
{
,而(真)
{
如果(CTS.Token.IsCancellationRequested)
{$! b $ b Thread.sleep代码(5000);
}
,否则
{
Console.WriteLine(线程取消);
中断;
}
};


解决方案

更新:
中的以下 MSDN 问题描述的原因:




传递一个令牌进入StartNew与工作
这样做有两个主要好处令牌关联:




  1. 如果令牌有取消
    要求开始执行之前的任务,任务不会
    执行,而是超过过渡到运行时,它会立刻
    过渡到取消。这样就避免了在运行任务,如果
    它只是同时反正跑被取消的费用。


  2. 如果在
    任务体也监测取消标记,并抛出包含令牌的
    OperationCanceledException(这是
    ThrowIfCancellationRequested 一样),那么当任务看到OCE,
    它会检查OCE的令牌是否匹配任务的令牌。如果
    呢,这个异常被视为合作
    取消的确认和任务转换到取消状态(而
    小故障状态)。




Here is a sample code that creates a new task that simulates a long running process.There is nothing much on the task as such and purely focuses on the cancelling features.I am using cancellation token to cancel the task and the code works fine for me.

       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);

    }
}

But onething that i could not understand is the token parameter(CTS.Token) that is being passed on to the Task Constructor.What is the actual use of passing the parameter,when i can actually cancel the task even without passing token to the constructor.

Down below is a slightly modified version that works without the token parameter.

      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;
               }
       };

解决方案

UPDATE: The following msdn question describes the reason:

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).

这篇关于什么是使用过的CancellationToken到任务类的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆