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 through 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 mind that if Async does not contain Await it will run synchronously.
private async void button_Click(object sender, RoutedEventArgs e)
{
HttpClient httpClient = new HttpClient();
await httpClient.GetStringAsync(stringUrl);
}
In the above code you can see we have used Async in button click 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.
private async void RunTask()
{
textBox1.Text = "Task is going to run";
System.Threading.Thread.Sleep(1000);
await Task.Factory.StartNew(() =>
{
RunningTask();
});
}
private void RunningTask()
{
this.Dispatcher.Invoke((Action)(() =>
{
textBox1.Text = "Dispatcher is working";
}));
}
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 available method but if you want to run your method with Aawait you can simply use Task.Factory and now you can do some other stuff while the code is running.
Summary:
- If your code needs some time to run, use Async and Await.
- If you want to update UI while Await method is working use Dispatcher.
- If you need to run a non available method as an available, use Task.Factory.
Read more articles on C#: