Asynchronous Tasks and Synchronization on UI TPL .Net 4.0

Using TPL for parallel programming is now a cup of cake. It made life easier for those who are new to multithreaded programming. A bunch of code lines can be encapsulated as an individual task using the Task class and you have the flexibility to run the task in either Sync or Async mode. In Sync mode the UI freezes for a moment until the task gets completed since all the other threads are blocked. So for a good user experience you don't want to let your application screen freezes for a moment so the Async task is a good choice in such case.
 
This post is to show how to notify the UI when the Asycn task gets completed. Absolutely you will want to get notified when you Asycn task has completed its work/execution.
 
Task.ContinueWith() is the function that will execute the next task after completion of the invoking task.
 
Syntax:
  1. .ContinueWith((result) => {  
  2.         //UI updation code to perform  
  3.     }, new CancellationTokenSource().Token, TaskContinuationOptions.None,  
  4.     //Right way to synchronize the UI with the completion of invoking task on ContinueWith  
  5.     TaskScheduler.FromCurrentSynchronizationContext()); 
Let's take an example of a simple windows forms application that can process images to generate the thumbnails:
 
First let design the UI like this:
 
Asynchronous Tasks and Synchronization on UI TPL .Net 4.0
 
[I'm still using WinForms just to save my time in creating demos .]
 
In the Form1.cs code behind file I've create a function called ProcessFilesInParallel() that will get enabled when the user selects the ParalledMode checkbox from the UI.  The MaintainQuality Checkbox is toggling in two functions and the limit files dropdown can limit the file processing and will Cancel the processing immediately if the limit is reached. I'm not going to explain the other functional code you can download the sample and analyze the code, but here we'll focus on  updating the UI while a task is in progress and when the task gets completed.
 
The main task to perform is to show the progress bar progressing and show a analytical summary of the task when completed. Below is the complete code of PracessfilesInParallel() method:
  1. private void ProcessFilesInParallel()  
  2. {  
  3.     ParallelOptions parOpts = new ParallelOptions();  
  4.     parOpts.CancellationToken = cancelToken.Token;  
  5.     parOpts.MaxDegreeOfParallelism = Environment.ProcessorCount;  
  6.   
  7.     string[] files = Directory.GetFiles(sourcePath, "*.jpg");  
  8.     long count = 0;  
  9.     totalfiles = files.Length;  
  10.     btnCancel.Visible = true;  
  11.     //--- Record the start time---  
  12.     DateTime startTime = DateTime.Now;  
  13.   
  14.     try  
  15.     {  
  16.         Task t1 = Task.Factory.StartNew(() =>  
  17.         {  
  18.             try  
  19.             {  
  20.                 Parallel.ForEach(files, parOpts, currentFile =>  
  21.                 {  
  22.                     //Check if cancellation requested  
  23.                     if (cancelToken.Token.IsCancellationRequested)  
  24.                     {  
  25.                         cancelToken.Token.ThrowIfCancellationRequested();  
  26.                     }  
  27.   
  28.                     string filename =Path.GetFileName(currentFile);  
  29.                               
  30.                     //Threadsafe updation to shared counter  
  31.                     count = Interlocked.Increment(ref count);  
  32.   
  33.                     if (islimited && fileLimit <= count)  
  34.                     {  
  35.                         cancelToken.Cancel();  
  36.                         // MessageBox.Show("Limit reached fileLimit = " + fileLimit + " Count=" + count);  
  37.                     }  
  38.   
  39.                     if (isQuality)  
  40.                         GenerateThumbnail(filename);  
  41.                     else  
  42.                         GetThumb(filename);  
  43.   
  44.                     //update the progress on UI  
  45.                      progressBar1.Invoke((Action)delegate { ReportProgress(count); });  
  46.                 });  
  47.             }  
  48.             catch (OperationCanceledException ex)  
  49.             {  
  50.                 progressBar1.Invoke((Action)delegate { ReportProgress(0); });  
  51.                 MessageBox.Show(ex.Message, "",MessageBoxButtons.OK, MessageBoxIcon.Warning);  
  52.             }  
  53.             //ContinueWith is used to sync the UI when task completed.  
  54.         }, cancelToken.Token).ContinueWith((result) =>  
  55.         {  
  56.             //Note the time consumed here  
  57.             TimeSpan elapsed = DateTime.Now.Subtract(startTime);  
  58.             TimeElapsed = (int)elapsed.TotalSeconds + " s : " + elapsed.Milliseconds + " ms";  
  59.             //finally update the UI with the summary result  
  60.             lblResult.Invoke((Action)delegate { lblResult.Text ="File Processed: " + count + " out of " + fileLimit + " Time Elapsed: " + TimeElapsed; });  
  61.         },new CancellationTokenSource().Token,TaskContinuationOptions.None,TaskScheduler.FromCurrentSynchronizationContext());  
  62.     }  
  63.     catch (AggregateException ae)  
  64.     {  
  65.         MessageBox.Show(ae.InnerException.Message, "",MessageBoxButtons.OK, MessageBoxIcon.Error);  
  66.     }  
As you can see I've used the control.Invoke() method because if you don't use it'll throw an error about cross thread operation is invalid or something like that. so you have to invoke the object in the currently executing thread.
 
Another important point is to use the TaskSchecutler.FromCurrentSynchronizationContext() function as a parameter as this is the best fit to use if you are going to update the  UI in the ContinueWith() task delegate.
 
Asynchronous Tasks and Synchronization on UI TPL .Net 4.0
 
So when you'll run the code the output would be something like this:
 
Asynchronous Tasks and Synchronization on UI TPL .Net 4.0
 
The code to show progress is also written in the function ProcessinParallel() method:
  1. //update the progress on UI  
  2. progressBar1.Invoke((Action)delegate { ReportProgress(count); }); 
Note - The sample attached has all the running code for you.
 
Asynchronous Tasks and Synchronization on UI TPL .Net 4.0
 
I hope you enjoyed this post cause I enjoyed creating this demo a lot.
 
Download the sample code.