Task Parallelism - Task OnCompleted trigger on after all ContinueWith

为君一笑 提交于 2019-12-24 02:12:31

问题


I am facing a problem on processing the task.GetAwaiter().OnCompleted(new Action)

I have a main task with multiple ContinueWith, but when i return the main task and add a delegate on the OnCompleted, it is triggered after the main task is processed and not after all the ContinueWith

My question is, is there a way to know when all the continue with is finished?

Here is my current code.

runningTask.Start();
    runningTask.GetAwaiter().OnCompleted(() =>
        {
             KeyValuePair<int, Func<bool>> validator = validationList.FirstOrDefault(x => x.Key == runningTask.Id);
             bool shouldContinue = validator.Value();
             if (shouldContinue)
             {
                  validationList.Remove(validator.Key);
                  PerformExecutionByQueue();
             }
         });

runningTask is created like this

Task runningTask = new Task(delegate method);
Task secondTask = runningTask.ContinueWith(delegate method);

and so on. . .


回答1:


Store the results of all of the calls to ContinueWith in a collection of some sort, and then use Task.WhenAll to execute some code when they have all finished.




回答2:


When you call ContinueWith, try passing in TaskContinuationOptions.AttachedToParent. That will tell the task to treat the continuation as part of the parent task, and to not complete the parent task until the continuation has also completed. This assumes, of course, the parent task has not already completed; if it has, the continuation will be executed inline when you call ContinueWith().




回答3:


ContinueWith creates a secondTask that will run only after runningTask is finished. secondTask does not prevent runningTask from finishing, so the OnCompleted event will fire immediatelly after runningTask finishes.

If you want to prevent runningTask from finishing while secondTask still runs, use TaskContinuationOptions.AttachToParent in ContinueWith, eg:

Task secondTask = runningTask.ContinueWith(delegate method,
                     TaskContinuationOptions.AttachToParent);

AttachToParent prevents its parent task from finishing until all child tasks have finished. An added bonus is that attached tasks will appear as child tasks under their parent in Visual Studio's Task View




回答4:


Fixed it by just adding an event on the class level and calling it on the last continue with.



来源:https://stackoverflow.com/questions/21856348/task-parallelism-task-oncompleted-trigger-on-after-all-continuewith

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!