这是否应该/是否可以"recursive Task"表示为任务延续?



在我的应用程序中,我需要在一些设置的间隔上连续处理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在完成后立即调用您的代码。这比手动轮询要快得多。

最新更新