【发布时间】: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<Task<Stuff>>,而不是Task<List<Stuff>>。伊万是对的。 -
您需要在
Task内部使用CancellationToken,而不是使用CancellationTokenSource。否则你有一个竞争条件(即)当你调用CTS.Cancel();并设置CTS = new ..你的旧任务可能/可能不会被取消,因为新的CTS.IsCancellationRequested将是错误的。
标签: c# task cancellationtokensource