这个“递归任务”应该/可以表示为TaskContinuation吗?

时间:2016-09-12 19:38:46

标签: c# recursion task-parallel-library

在我的应用程序中,我需要在某些设置间隔内不断处理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:链来表示吗? 这样的实施会有什么好处吗?当前的实施有什么重大错误吗?

1 个答案:

答案 0 :(得分:1)

调用ContinueWith告诉Task在完成代码后立即调用您的代码。 比手动轮询更快