Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
var tasks = Items.Select(i=> Task.Factory.StartNew(()=> i.DoSomething()));
Task.WaitAll(tasks.ToArray());

In the above code, What happens when DoSomething is too short that it ends before WaitAll is called. (Items are off different sub-classes with different implementations)
Posted
Comments
Rob Philpott 17-Aug-15 11:36am    
Unlikely to happen - the effort of spinning it off on a thread will take longer than hitting the next instruction. But either way, WaitAll will wait, if necessary, until all tasks are complete. If they are already complete, it will just step over it.

1 solution

A task supports for instance the property IsCompleted and a Status containing a TaskStatus value of which several can be completed i.e. completed with or without fault.
https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx[^]

The Task.WaitAll takes an array of tasks and waits for all of them to complete.
https://msdn.microsoft.com/en-us/library/dd270695(v=vs.110).aspx[^]

In the very unlikely case that a Task will actually spin up and return before the next statement in the crating code, the implementation of WaitAll will still wait until all have completed and in this case the first check for completion succeeds and the code will simply continue from the next line. In your example code 'nothing' will happen as you did not include the next statement, which is just the same as if indeed it took marginally longer to complate than the await to enter it's monitor loop
 
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