Repeated task continuation

I would like to understand this scenario a little clearer:

Consider the following code:

frmProgressAsync prog = new frmProgressAsync(true); TaskWithProgress t = new TaskWithProgress("Smoothing CP", true); t.Task = A.ShowMovingAverage(tension,t.Progress) .ContinueWith(prev => { t.ProgressInformation.Report("Smoothing FG"); B.ShowMovingAverage(tension, t.Progress); }); await prog.RunAsync(t); 

I have two tasks that I want to run A.ShowMovingAverage and B.ShowMovingAverage . Both return a task.

In the prog.RunAsync() method, I have the following:

  public virtual Task RunAsync(TaskWithProgress task) { Show(); TaskIsRunning(); task.ContinueWith(Close(), CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, this._Scheduler); return task.Task; } 

So, I have three tasks that need to be run alternately after completing the previous one.

Now my problem in some cases, the first task is completed almost immediately. When the prog.RunAsync() call is prog.RunAsync() and the final continuation is added to the task, it starts immediately, closing the form.

I can find out if I failed on the last call to ContinueWith() , the state of the RanToCompletion task, but I kind of expect it to continue until reset, so that it continues.

Can someone explain this behavior a little more cleanly? And provide a potential solution so that all tasks (continuations) are completed before the final continuation?

+1
source share
1 answer

Tasks are completed only once. When you attach a continuation, you create a new task that begins with the completion of the antecedent task. So, I believe that the problem you see is that RunAsync supports the continuation of Close , but does nothing with the task of continuing; consider task.Task = task.ContinueWith(Close(), ...) .

However, I recommend using await instead of ContinueWith . I find that usually clarifies the code and makes it easier to understand.

 frmProgressAsync prog = new frmProgressAsync(true); TaskWithProgress t = new TaskWithProgress("Smoothing CP", true); t.Task = ShowMovingAveragesAsync(A, B, tension, t.Progress); await prog.RunAsync(t); private async Task ShowMovingAveragesAsync(TA A, TA B, TT tession, IProgress<string> progress) { progress.Report("Smoothing FG"); await A.ShowMovingAverageAsync(tension, progress); progress.Report("Smoothing FG"); await B.ShowMovingAverageAsync(tension, progress); } public virtual async Task RunAsync(TaskWithProgress task) { Show(); TaskIsRunning(); await task; Close(); } 
+4
source

All Articles