Control Current Tasks In Multithreading

Introduction

Tasks are created and maintained explicitly by developers. Developers can control the tasks or process the return values. So, they have control over the the behavior of Task. Microsoft provides bunch of methods to control current Tasks.


Below are the methods which are being used to control current Task:

Start()

It starts the task and schedules for the execution.
 
Example
  1. public void StartTask()    
  2. {    
  3.     Task<int> task = new Task<int>(obj =>    
  4.     {    
  5.         int myTotal= 0;    
  6.         int max = (int)obj;    
  7.         for (int i = 0; i < max; i++)    
  8.         {    
  9.             myTotal += i;    
  10.         }    
  11.         return myTotal;    
  12.     }, 400);    
  13.   
  14.     task.Start();    
  15.   
  16.     int result = Convert.ToInt32(task.Result);    
  17.     Console.WriteLine("Total  {0}", result);    
  18. }    
So, here task.Start() method will start the task and we specified that we want result from 0 to 400.

Wait()

It waits for the Task to complete execution. It is a synchronization method that causes the calling thread to wait until the current task has completed.
Below are the reasons for which we will apply Wait() method:
  1. If main thread depends on the final result completed by the given Task.
  2. If you want to handle exception that might be thrown by Tasks.
Below are the some methods of wait:
  1. public void TaskWithWait()    
  2. {    
  3.     var parent = Task.Factory.StartNew(() =>    
  4.     {    
  5.         Console.WriteLine("Main Task Started...");    
  6.         for (int value = 0; value < 10; value++)    
  7.         {    
  8.             int myTaskNo = value;    
  9.             Task.Factory.StartNew((x) =>    
  10.             {    
  11.                 Console.WriteLine("Child Task {0} completed.",    
  12.                                   x);    
  13.             },    
  14.                                   myTaskNo, TaskCreationOptions.AttachedToParent);    
  15.         }    
  16.     });    
  17.   
  18.     parent.Wait();    
  19.     Console.WriteLine("Main task completed.");    
  20. }  
Output:

Main Task Started...
Child Task 9 Completed.
Child Task 0 Completed.
Child Task 8 Completed.
Child Task 1 Completed.
.......................................
Main Task Completed...

So, here Main Task did wait for the complete of Child Task.

WaitAll

It is used to block all tasks to complete.

Example:
  1. Task[] tasks = new Task[3]      
  2. {      
  3.     Task.Factory.StartNew(() => MyMethodA()),      
  4.     Task.Factory.StartNew(() => MyMethodB()),      
  5.     Task.Factory.StartNew(() => MyMethodC())      
  6. };      
  7.       
  8. Task.WaitAll(tasks);  
ContinueWith()

It starts new task after the complete status of current task.

Example:
  1. public void TaskContinueWith()    
  2. {    
  3.   
  4.     Task<DayOfWeek> myTask = new Task<DayOfWeek>(() => DateTime.Today.DayOfWeek);    
  5.   
  6.   
  7.     Task<string> continuation = myTask.ContinueWith((antecedent) =>    
  8.     {    
  9.         return String.Format("Today is {0}.", antecedent.Result);    
  10.     });    
  11.   
  12.     taskA.Start();    
  13.   
  14.     Console.WriteLine(continuation.Result);    
  15. }    
Output

Today is Friday.

RunSynchronously()

By Default Task runs asynchronously. But, this method runs Task synchronously. For more details about RunSynchronously() method of Task please visit the following link.

Conclusion

So, these methods provide way to control Task. Developer can easily control the Task as per requirements.
 
Read more articles on Multithreading:


Similar Articles