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.
- 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 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 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:
- If your code needs some time to run, useAasync and Await.
- If you want to update UI while Await method is working use Dispatcher.
- If you need to run a non awaitale method as an awaitable, use Task.Factory.
Read more articles on C#: