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
- Task t1 = new Task(() =>
- {
- test();
- });
- t1.Start();
- t1.Wait();
- System.Diagnostics.Debug.WriteLine("Task Ended");
- public void test()
- {
- Task.Delay(TimeSpan.FromSeconds(15)).Wait();
- System.Diagnostics.Debug.WriteLine("Task Completed");
- }
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
- test();
- System.Diagnostics.Debug.WriteLine("End of Main");
- public async void test()
- {
- Task t = new Task(
- () =>
- {
- Task.Delay(TimeSpan.FromSeconds(15)).Wait();
- System.Diagnostics.Debug.WriteLine("Ended the task");
- });
- t.Start();
- await t;
- System.Diagnostics.Debug.WriteLine("After await");
- }