在我的应用程序中,我需要在某些设置间隔内不断处理Work
的某些部分。我最初写了一个Task
来不断检查给定的Task.Delay
以查看它是否已完成,如果是,则会Work
处理与Task.Delay
相对应的Task
。回退到此方法的是Task.Delays
,当没有Task.Delay
完成时,检查这些Task
将处于伪无限循环中。
为了解决这个问题,我发现我可以创建一个“递归// New Recurring Work can be added by simply creating
// the Task below and adding an entry into this Dictionary.
// Recurring Work can be removed/stopped by looking
// it up in this Dictionary and calling its CTS.Cancel method.
private readonly object _LockRecurWork = new object();
private Dictionary<Work, Tuple<Task, CancellationTokenSource> RecurringWork { get; set; }
...
private Task CreateRecurringWorkTask(Work workToDo, CancellationTokenSource taskTokenSource)
{
return Task.Run(async () =>
{
// Do the Work, then wait the prescribed amount of time before doing it again
DoWork(workToDo);
await Task.Delay(workToDo.RecurRate, taskTokenSource.Token);
// If this Work's CancellationTokenSource is not
// cancelled then "schedule" the next Work execution
if (!taskTokenSource.IsCancellationRequested)
{
lock(_LockRecurWork)
{
RecurringWork[workToDo] = new Tuple<Task, CancellationTokenSource>
(CreateRecurringWorkTask(workToDo, taskTokenSource), taskTokenSource);
}
}
}, taskTokenSource.Token);
}
”(我不确定这是什么行话),它会根据需要以给定的间隔处理工作。
Task.ContinueWith
应该/可以用default:
链来表示吗? 这样的实施会有什么好处吗?当前的实施有什么重大错误吗?
答案 0 :(得分:1)
是!
调用ContinueWith
告诉Task
在完成代码后立即调用您的代码。 远比手动轮询更快