Async/Await .Net Core
Async/Await is one of the most used words in developers’ instances when it comes to handling functions and data through either network, database, or file systems. Async word is derived from asynchronous which is contrary to synchronous. Usually, we write code in a sequence way, In .net default methods we create are synchronous.
So synchronous methods wait for the completion of the methods before executing the next operation. Let’s try a basic example of preparing breakfast.
- Heat the water
- Make coffee
- Heat the pan
- Make an omelet
- Eat breakfast
So if we are working synchronously first we have to heat water after the water is heated make coffee, then toast bread, then make an omelet, and finally eat breakfast. In real life, we don’t do this sequentially. We can complete these tasks parallelly. And that is asynchronous.
Here I have created a console application that describes the process of making breakfast. The below image is the output of the above code
As this shows the code ran synchronously. Let’s see the same example using the asynchronous method.
Asynchronous mainly use async and await followed by a task which allows it to work asynchronously. Here while boiling the water (2000 mc delay) we can complete make omelet process and complete the tasks parallelly.
To understand asynchronous let’s deep dive through different examples. Here we can go through some important topics like thread pool, machine state, etc.
static async Task Main(string args)
var clinet = new HttpClient();
var URL = clinet.GetStringAsync(“https://dog.ceo/api/breeds/image/random");
Console.WriteLine(“Doing other task”);
var data = await URL;
This is a normal async example we use regularly. We are getting data from the URL and while retrieving that data we can do another task. If we decompile this code we can see the thread handling clearly. Here I used ILSpy to decompile the code and get it in a readable way.
Once we use async and await our main functions become an object and its fields as In the above image
The code basically chopped into 2 parts 1 is till the await and the other part is after await.
Before we go into details first we have to understand what is thread pool. A Thread pool is basically a list of threads that the system pre-created and ready to execute but does not execute. This is managed by the .Net runtime. The thread pool assigns and reassigns tasks to threads and maintains them.
<URL>5__2 = <clinet>5__1.GetStringAsync(“https://dog.ceo/api/breeds/image/random");
As in the above example when the URL is called it’s assigned by thread it goes through the operating system and to the network drive( 2). Then that thread is released and comes back to the thread pool and assigned to another task or it goes to sleep. Then the code continues. and it checks if that URL call is completed or not.
num = (<>1__state = 0);
<>u__1 = awaiter;
<Main>d__0 stateMachine = this;
<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
If not completed it updates a state in the state machine. Which is inserted into RAM. When the URL returns the response data(4), it notifies the thread pool (5)and the thread pool finds the state machine in RAM memory and calls the MoveNext() function. When it returns the num value is 0 and it completes the code execution
<>s__4 = awaiter.GetResult();
<data>5__3 = <>s__4;
<>s__4 = null;
As the above examples explain the usage of asynchronous programming the main advantage is an increase of performance in complex programs because of the handling of threading.
Let’s dive into a real-world example
Here explaining file upload functionality with the progress bar in a Blazor application.
As we can we are uploading multiple files and showing the progress of the upload in a progress bar. While we are reading files its incrementing upload bites in a while loop and simultaneously it’s showing in the ui using UploadedBytes.
Here we are using to await method
- One is to update ui every 500 milliseconds so the ui is updated with the latest details(progress)
- The other one is to read the upload file and record currently uploaded bytes to increase the progress
This is a small sample showcase for the use of async await.