Home > Back-end >  What is the use of async/await method calls?
What is the use of async/await method calls?

Time:09-17

In my project's code base, I see a lot of methods that boil down to the following code:

public async Task<bool> MyAsyncFunction(string filePath) 
{
   byte[] fileBytes = await File.ReadAllBytesAsync(filePath);
   bool succeeded = await UploadFileSomewhereAsync(fileBytes);

   return succeeded;
}

I understand that async/await is useful for non-blocking UI tasks in front-end code. I also understand that async/await can be used to run certain tasks in parallel, as in the code below:

public async Task<bool> MyAsyncFunction(string filePath) 
{
   Task<byte[]> fileBytesTask = File.ReadAllBytesAsync(filePath);

   // do some other work that does not need the file byte array

   byte[] fileBytes = await fileBytesTask;
   bool succeeded = await UploadFileSomewhereAsync(fileBytes);

   return succeeded;
}

However, how is the async/await pattern of any use in the first example? Is there any benefit of writing code like this over simply calling the synchronous versions of these methods? Am I missing something?

CodePudding user response:

To expand a bit on Stephen Clearys comment

There are two main use cases for asynchronous code.

  1. For UI applications you do not want to freeze your UI while doing some slow IO-operation, like reading a large file, or doing something process intensive.
  2. For server applications you do not want to consume a thread while waiting for slow IO operations. Many servers are fairly simple front ends for a database. If you have 1000 concurrent queries and are using synchronous code, you might require 1000 threads that are just waiting. Threads uses some resources, like memory, and this becomes wasteful when trying to service a large number of concurrent users.

The older styles of doing writing asynchronous code was a bit difficult to use, since you need to manually keep track of everything that is needed to be done after the IO operation completed. Async/awaits largely avoids this by making the compiler do the difficult parts, letting you write code that looks like regular sequential code.

A criticism against async/await is that sometimes it is better to use synchronous methods. So you might be required to write two versions of essentially the same code.

  • Related