Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
A very good morning to all.

I want to check I'm not missing something. I'm looking at a lot of code which is following the pattern of kicking a task off, then in a continuation there is a call to wait on the task being continued from (the antecedent, to be a good M$ citizen).

This seems bonkers to me as the continuation should only run once the first task completes, and we all see bonkers code the whole time, but then there's this:

http://msdn.microsoft.com/en-us/library/dd270696(v=vs.110).aspx[^]

which has this bit at the bottom:
Task.WaitAll( new Task[] {dTask, dTask2} );


..which waits for the initial task and its continuation to finish. Now, if this is purely to block the calling thread until the process is complete surely only the second task needs waiting on.

This may be good practice to catch exceptions or for some other reason. No real question there, but opinions welcome, what do you think? Thanks.
Posted
Updated 2-Jan-14 23:52pm
v2

1 solution

It does look odd, though the explanation below the code may shed some light:

"Because a console application may terminate before the continuation task executes, the WaitAll method is called to ensure that both the original task and its continuation finish executing before the example ends."

In other words, waiting on both dTask and dTask2 is there to guard against a situation in which dTask completes and dTask2 has not started execution yet, as the console app will not be able to wait on dTask2 returned by Task.Factory.StartNew()

It might be worth bearing in mind that dTask2 does not execute in itself but rather kicks-off an asynchronous task. In this respect, dTask2 can be viewed as a wrapper which spawns an inner task, and calls Task.Run() on this inner task. Waiting on dTask2 would not work, as it immediately returns after spawning off the inner task. It should be possible to unwrap dTask2 and wait on its inner task, though this is probably not what is intended here - being as tasks were created using Task.Factory rather than more directly using the constructor. Here is an interesting blog which is centred around this topic:
Task.Run vs Task.Factory.StartNew, by Stephen Toub[^]

Some of this complexity, perhaps, stems from dTask2 being asynchronous. It would be interesting to explore whether this could be avoided by running dTask and dTask2 in sequence continuation (as opposed to parallel continuation) using the fluent interface pattern, chaining .ContinueWith(dTask2 => ... onto Task.Factory.StartNew()
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900