async methods help avoid unresponsiveness

What are async await keywords? Why are they important?

Sriram Kumar Mannava
2 min readMar 29, 2023

--

Imagine you are writing a functionality to upload a file to the disk. It is an IO operation where you create a file, write bytes and save to the system.

Let's assume the operation takes an average of 10 seconds.

That means the main thread (the process that runs your application) is working on this operation for 10 seconds.

But there could be other requests coming to your application to be processed.

If the IO operation is synchronous - meaning the process does only one thing at a time and in sequence, chances are that the other concurrent requests are rejected; or the application becomes unresponsive.

This is called a blocking operation.

async await keywords are used for creating asynchronous operations.

awaiting a process puts in a separate task and returns the reference to that task.

Once complete the runtime makes sure that the process starts execution back from where the await process occurs.

This is called as continuation.

In this case, while the asynchronous operations are performed in a separate process, the main process is still open for other requests.

This is very important for a server resource that handles millions of requests concurrently, without being unresponsive.

You will mark a method that is asynchronous with the async keyword. While calling this method, you will await it.

What if I have multiple async methods to await?

we can use Task.WhenAll() method over a list of Tasks, which will ensure all the calls within the collection are completed before flagging as complete.

For example,

var tasks = new List<Task<int>>();

for (int i = 0; i < 10; i++)
{
tasks.Add(Task.Run<int>(() =>
{
Thread.Sleep(100);
return i;
}));
}

int[] task = await Task.WhenAll(tasks);

foreach (var i in task)
{
Console.WriteLine(i);
}

--

--

Sriram Kumar Mannava
Sriram Kumar Mannava

Written by Sriram Kumar Mannava

I make Full Stack Development Easy for You | Full Stack .NET Dev | 3× AWS Certified | Blogger

No responses yet