Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ContinueWhenAll doesn't wait for all task to complete

I have found a piece of code on the web and have modified it a bit to see how it works, but now I have a problem with ContinueWhenAll as it doesn't wait for all tasks to be finished:

List<Task> tasks = new List<Task>();
for (int i = 0; i < 20; i++)
{
    int j = i;
    var compute = Task.Factory.StartNew(() => results.Add(DoSomething(j)));
    tasks.Add(compute);
}

I'm using this code to add all task to list. DoSomething function computes some results and adds them to BlockingCollection. I have another display function which writes all added results from BlockingCollection to the console.

I have used this code to wait for all tasks to complete, but it looks like it doesn't wait for them as the program displays the standard "Press any key to continue" message just a few milliseconds after it was started. (It should take ~20 sec for program to complete)

Task.Factory.ContinueWhenAll(tasks.ToArray(), result => results.CompleteAdding());

However if I add Task.WaitAll(consume) to end of the program, program works fine:

var consume = Task.Factory.StartNew(() => display(results));
//results = BlockingCollection that I mentioned 

As far as I understand, the program will not have enough time to display all result from BlockingCollection but still it has more than enough time to display some while waiting for all tasks to complete.

Could someone explain me why Task.Factory.ContinueWhenAll doesn't wait for all results to be computed and program comes to an end just like there is no that line of code in program (after few milliseconds)?

like image 488
Dan Avatar asked Jul 23 '11 00:07

Dan


1 Answers

Task.Factory.ContinueWhenAll is not a blocking method; it will actually start a new task that will only function when all the provided tasks complete there execution, So it is normal to see a message just a few milliseconds after program has been started, because it will not block at your main waiting for the tasks to finish. From msdn:

Creates a continuation Task that will be started upon the completion of a set of provided Tasks.

Where the Task.WaitAll will block at the caller waiting for all of the provided Tasks to complete execution.

like image 150
Jalal Said Avatar answered Nov 06 '22 09:11

Jalal Said