Working With Async, Await, And Dispatcher In C#

Today's article is about Async and Await and how one can update their UI while Async and Await are doing their job. First let's  take a look at Async and Await. While working in WPF you may go throught long calculations, like if you are trying to get a response from a web uri, your UI may get blocked and the user will not be able to minimize the window anymore. It happened with me. Async and Await are used where the method does not immediately return. The Async method can only return a void or Task<>.

Here you must keep in ind that if Async does not contain Await it will run synchcronously.

  1. private async void button_Click(object sender, RoutedEventArgs e)  
  2.         {  
  3.             HttpClient httpClient = new HttpClient();  
  4.            await httpClient.GetStringAsync(stringUrl);  
  5.         }  
In the above code you can see we have used Async in button click and and Await to get the response from the url. We are able to use Async here in button click because it is void.

Here comes another scenario in which you need to update the UI thread while the Await method is working; below is a piece of code.
  1. private async  void RunTask()  
  2.         {  
  3.             textBox1.Text = "Task is going to run";  
  4.             System.Threading.Thread.Sleep(1000);  
  5.             await Task.Factory.StartNew(() =>  
  6.             {  
  7.                 RunningTask();  
  8.   
  9.             });  
  10.   
  11.         }  
  12.   
  13.         private void RunningTask()  
  14.         {  
  15.             this.Dispatcher.Invoke((Action)(() =>  
  16.             {  
  17.                 textBox1.Text = "Dispatcher is working";  
  18.             }));  
  19.         }  
Look, RunTask is working with Async and Await; while it is working with RunningTask we can update our UI by using Dispatcher. The code inside Dispatcher will help UI to be updated.

Here you can also notice that RunningTask() is not an awaitable method but if you want to run your method withAawait you can simply use Task.Factory and now you can do some other stuff while the code is running.

Summary: 
  1. If your code needs some time to run, useAasync and Await.
  2. If you want to update UI while Await method is working use Dispatcher.
  3. If you need to run a non awaitale method as an awaitable, use Task.Factory.
Read more articles on C#: