Should/Could this“递归任务”;表示为TaskContinuation
本文关键字:表示 TaskContinuation 递归任务 任务 Could this 递归 Should | 更新日期: 2023-09-27 18:06:38
在我的应用程序中,我需要在一些设置的间隔上连续处理Work
的一些片段。我最初写了一个Task
来不断检查给定的Task.Delay
,看看它是否完成了,如果是这样,Work
将被处理,对应于Task.Delay
。这个方法的缺点是Task
检查当没有Task.Delay
完成时,Task.Delays
将处于伪无限循环中。
为了解决这个问题,我发现我可以创建一个"递归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
链来表示吗?这样的实现会有什么好处吗?当前的实现有什么主要错误吗?
是!
调用ContinueWith
告诉Task
在完成后立即调用您的代码。这比手动轮询要快得多。