【问题标题】:cancelling tasks with cancellation tokens使用取消令牌取消任务
【发布时间】:2014-08-15 08:23:20
【问题描述】:

我有一个任务来获取我的数据。我有另一个属性,如果更改会取消任务并再次启动任务,但参数不同,如下所示。

private CancellationTokenSource CTS = new CancellationTokenSource();

private void LoadMyStuff(string parameter)
{          
     Task<List<Stuff>> loadStuff = new Task<List<Stuff>>(() => ServiceMethod(parameter));
     loadStuff.Start();
     loadStuff.ContinueWith((Sender) =>
     {
           foreach (var entry in Sender.Result)
           {
               if (!CTS.IsCancellationRequested)
               {
                   //Proccess my data      
               }
               else
               {
                   CTS.Cancel();
                   return;
               }
            }
     }, CTS.Token, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());
     loadStuff.ContinueWith((Sender) =>
     {
          //Clean Up
     }, CTS.Token, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
 }

属性:

private Thing _myThing
public Thing MyThing
{
   get { return _myThing; }
   set 
     {
        _myThing= value;
        CTS.Cancel();
        LoadMyStuff(parameter); 
     }
}

所以我的问题是,在这种情况下,我总是在任务完成之前取消它。如何获得这样的场景:任务的第一个实例取消但从MyThing 属性触发的第二个实例一直运行到完成?

【问题讨论】:

  • 如果我理解正确,您应该为每个任务创建一个新的 CanceltionTokenSource。
  • 您能澄清一下每“批次”任务的含义吗?
  • @user1 没关系,我以为您创建的是List&lt;Task&lt;Stuff&gt;&gt;,而不是Task&lt;List&lt;Stuff&gt;&gt;。伊万是对的。
  • 您需要在Task 内部使用CancellationToken,而不是使用CancellationTokenSource。否则你有一个竞争条件(即)当你调用CTS.Cancel(); 并设置CTS = new .. 你的旧任务可能/可能不会被取消,因为新的CTS.IsCancellationRequested 将是错误的。

标签: c# task cancellationtokensource


【解决方案1】:

你必须创建一个新的CancellationTokenSource

一旦CancellationTokenSource 发出信号,它的所有令牌也会发出信号,并且它们将保持这种状态。 所以如果你想开始一个新的任务,你需要一个全新的代币来源。

【讨论】:

  • 所以如果我在我的MyThing 属性中正确理解这一点,我应该这样做CTS.Cancel(); 然后CTS = new CancellationTokenSource(); 然后LoadMyStuff();
  • @user1 这是一种可能的解决方案,但我不喜欢这种设计。想想责任。重置令牌源不是MyThing 的责任。我认为LoadMyStuff应该是方法启动时重置令牌源的那个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
  • 2019-09-10
  • 1970-01-01
相关资源
最近更新 更多