Difference between continuewhenAll and WaitAll


This is a part of the blog series , “Asynchronous Programming Using DotNet” .Please visit this page to see the “index” of all the posts I wrote on this series.

So what exactly is the difference between continuewhenAll and WaitAll method ? When and where should you use them?

Consider the following piece of code

   1: int start = Environment.TickCount;

   2:

   3: Task T1 = Task.Factory.StartNew(() =>

   4:

   5: {

   6:

   7: Thread.Sleep(3000);

   8:

   9: });

  10:

  11: Task T2 = Task.Factory.StartNew(() =>

  12:

  13: {

  14:

  15: Thread.Sleep(3000);

  16:

  17: });

  18:

  19: Task T3 = Task.Factory.StartNew(() =>

  20:

  21: {

  22:

  23: Thread.Sleep(3000);

  24:

  25: });

  26:

  27: Task[] T_Arr = { T1, T2,T3 };

  28:

  29: Task.WaitAll(T_Arr);

  30:

  31: int stop = Environment.TickCount;

  32:

  33: textBox1.Text =( stop - start).ToString();

The time of run is a little over 3000 miliseconds.

clip_image002

As you can see, Task.waitAll takes an array as an argument and waits till all the tasks are complete. The tasks itself are asynchronous in nature. So the period of waiting is roughly equal to the maximum of (Time taken by T1, Time Taken by T2, and Time Taken by T3).During the waiting period the UI freezes ,as the UI thread is busy waiting!! So basically even though the tasks are done asynchronously, the waiting is synchronous.

So what is the solution ?

The new code is

   1: TaskFactory tf = new TaskFactory();

   2:

   3: tf.ContinueWhenAll(T_Arr, (a) =>

   4:

   5: {

   6:

   7: int stop = Environment.TickCount;

   8:

   9: textBox1.Text = (stop - start).ToString();

  10:

  11: }, new CancellationToken(), TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

Continuewhen all typically starts a new thread.Continuewhenall delegate will be called once the tasks are finished and the contents of the continuewhen all will run on a new thread.So there is synchronous waiting.Here in our case ,since we are updating the UI, the task will run on the UI thread,but while waiting for the output it won’t be blocking the UI thread, Hence your application remains responsive, even if your tasks are not complete.

Advertisements

One response to “Difference between continuewhenAll and WaitAll

  1. Pingback: Asynchronous Programming Series | Using Abhik.Mitra.myThoughts;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s