Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait on all tasks (created task and subtask) without using TaskCreationOptions.AttachedToParent

I will have to create a concurrent software which create several Task, and every Task could generate another task(that could also generate another Task, ...).

I need that the call to the method which launch task is blocking: no return BEFORE all task and subtask are completed.

I know there is this TaskCreationOptions.AttachedToParent property, but I think it will not fit:

The server will have something like 8 cores at least, and each task will create 2-3 subtask, so if I set the AttachedToParent option, I've the impression that the second sub-task will not start before the three tasks of the first subtask ends. So I will have a limited multitasking here.

So with this process tree:

enter image description here

I've the impression that if I set AttachedToParent property everytime I launch a thread, B will not ends before E,F,G are finished, so C will start before B finish, and I will have only 3 actives thread instead of the 8 I can have.

If I don't put the AttachedToParent property, A will be finished very fast and return.

So how could I do to ensure that I've always my 8 cores fully used if I don't set this option?

like image 402
J4N Avatar asked Jul 05 '12 10:07

J4N


2 Answers

The TaskCreationOptions.AttachedToParent does not prevent the other subtasks from starting, but rather prevents the parent task itself from closing. So when E,F and G are started with AttachedToParent, B is not flagged as finished until all three are finished. So it should do just as you want.

The source (in the accepted answer).

like image 85
Me.Name Avatar answered Sep 20 '22 21:09

Me.Name


As Me.Name mentioned, AttachedToParent doesn't behave according to your impressions. I think it's a fine option in this case.

But if you don't want to use that for whatever reason, you can wait for all the child tasks to finish with Task.WaitAll(). Although it means you have to have all of them in a collection.

Task.WaitAll() blocks the current thread until all the Tasks are finished. If you don't want that and you are on .Net 4.5, you can use Task.WhenAll(), which will return a single Task that will finish when all of the given Tasks finish.

like image 40
svick Avatar answered Sep 22 '22 21:09

svick