这个“递归任务"应该/可以吗?表示为 TaskContinuation? [英] Should/Could this "recursive Task" be expressed as a TaskContinuation?

查看:55
本文介绍了这个“递归任务"应该/可以吗?表示为 TaskContinuation?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我需要在某个设定的时间间隔内连续处理一些Work.我最初编写了一个 Task 来不断检查给定的 Task.Delay 以查看它是否已完成,如果完成,将处理 Work对应于 Task.Delay.此方法的缺点是 Task 会检查这些 Task.Delays 在没有 Task.Delay 时是否处于伪无限循环中完成.

In my application I have the need to continually process some piece(s) of Work on some set interval(s). I had originally written a Task to continually check a given Task.Delay to see if it was completed, if so the Work would be processed that corresponded to that Task.Delay. The draw back to this method is the Task that checks these Task.Delays would be in a psuedo-infinite loop when no Task.Delay is completed.

为了解决这个问题,我发现我可以创建一个递归Task"(我不确定这个的术语是什么),根据需要在给定的时间间隔内处理工作.

To solve this problem I found that I could create a "recursive Task" (I am not sure what the jargon for this would be) that processes the work at the given interval as needed.

// 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 在完成后立即调用您的代码.这比手动轮询要.

Calling ContinueWith tells the Task to call your code as soon as it finishes. This is far faster than manually polling it.

这篇关于这个“递归任务"应该/可以吗?表示为 TaskContinuation?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆