How And When To Use Task And Async Await

In this article, we are going to see how and when to use Task and Async Await in C# application. Here, we will be using Windows 10 UWP app.

Task and Async-Await features help to deal with asynchronous calls. In most of the software client applications in which we are communicating with the server to read or update some data, we need to block/allow users to do some other operation until we get the data from Server.

When to use Task?

Task.Wait is a blocking call. It blocks the thread until the task is complete, and ignores all other operations while you are waiting for the task completion. By default, the task runs on a thread from a thread pool. If you are willing to block user interaction or ignore the other operations, it is better to use Task.

Eg

  1. Task t1 = new Task(() =>  
  2. {  
  3.     test();  
  4. });  
  5. t1.Start();  
  6. t1.Wait();  
  7. System.Diagnostics.Debug.WriteLine("Task Ended");  
  8. public void test()  
  9. {  
  10.     Task.Delay(TimeSpan.FromSeconds(15)).Wait();  
  11.     System.Diagnostics.Debug.WriteLine("Task Completed");  
  12. }  
Here, Task t1 runs the test method and waits until the test method finishes the task. It blocks all other operations. Once the test method is completed, it will print “Task Ended” and when the users try to do some other operations, it will ignore them until it completes the task. We can set the time also, for the task to finish.

When to use async-await ?

async and await feature simplifies the asynchronous call. It keeps processing the main thread, which means not blocking the main thread, and allows you to process the other operations in the queue. If you are willing to allow your application to do some other operations until the main task completion, you can use async-await.

Eg
  1. test();  
  2. System.Diagnostics.Debug.WriteLine("End of Main");  
  3. public async void test()   
  4. {  
  5.     Task t = new Task(  
  6.         () =>   
  7.         
  8.         {  
  9.             Task.Delay(TimeSpan.FromSeconds(15)).Wait();  
  10.             System.Diagnostics.Debug.WriteLine("Ended the task");  
  11.         });  
  12.     t.Start();  
  13.     await t;  
  14.     System.Diagnostics.Debug.WriteLine("After await");  
Here, the string "End of Main" is printed before "Ended the task" and “After await”. You can see that during the waiting period, the main thread is not blocked and it continues the other operations.

 

Ebook Download
View all
Learn
View all