Asynchronous programming with .NET Core – Async and Await

Asynchronous programming is an important part in today’s programming world that allows efficient use of system resources and responsiveness of applications. In this article, we will walk through the asynchronous programming with .NET Core, including the benefits with examples to illustrate the concept.

Asynchronous programming with .NET Core – Async and Await

Asynchronous programming is the ability to perform multiple tasks concurrently, without blocking the execution thread. The .NET Core provides support for asynchronous programming using the async and await keywords, which allow developers to write asynchronous code in a simpler and more readable manner.

How Async and Await works?

In .NET Core, asynchronous programming is achieved using the async and await keywords, which allow developers to write asynchronous code that looks like synchronous code.

Before we start looking at Async and Await, let’s investigate the problem statement. What happends exactly if we don’t have Async and Await in .NET, let’s consider the below example:

PerformLongJob();
Console.WriteLine("Finished!");
Console.ReadLine();

void PerformLongJob()
{
    System.Threading.Thread.Sleep(5000);
    Console.WriteLine("Long Run Job Done.");
}

When you run the above example, the output we see as: 

Without Asynchronous problem

In the above example you can see that, first we are calling PerformLongJob() method and next printing the finished message to console window. The program executed synchronously and printed messages sequentially, which means that program blocks current thread to complete the operation from PerformLongJob() and waited until this method is completed, then moved to next line to print the further message.

Now to understand the Async and Await better way, let’s change the program to convert the long run method as asynchronous method as below.

PerformLongJob();
Console.WriteLine("Finished!");
Console.ReadLine();

async void PerformLongJob()
{
    await Task.Run(() =>
    {
        System.Threading.Thread.Sleep(5000);
        Console.WriteLine("Done with long running job.");
    });
}

Now if you run the above program, the result you will see as below:

With Asynchronous problem Solved

When you look at above output console window, first finished message has written to console which means that program didn’t block the current thread to execute PerformLongJob(), instead it ran the asynchronous method in a separate thread safely.

Asynchronous programming is supported in many .NET Core libraries and frameworks as well, including ASP.NET Core, Entity Framework Core, and HttpClient.

Asynchronous methods

Asynchronous methods are defined using the async keyword, which allows the method to be executed asynchronously without blocking the execution thread. Asynchronous methods return a Task or Task<T> object, which represents the asynchronous operation.

Here's an example of an asynchronous method that performs a file read operation:

string path = @"C:\temp\log.txt";
string contents = await ReadFileAsync(path);
Console.WriteLine(contents);
Console.ReadLine();

async Task<string> ReadFileAsync(string path)
{
    using (StreamReader reader = new StreamReader(path))
    {
        return await reader.ReadToEndAsync();
    }
}

The async keyword in the method signature indicates that the method can be executed asynchronously. The Task<string> return type indicates that the method returns a Task object that will eventually yield a string result. The await keyword is used to wait for the completion of the ReadToEndAsync() method, which performs the file read operation asynchronously.

Asynchronous operations

Asynchronous operations are performed using the await keyword, which allows the execution thread to continue with other tasks while the operation is performed asynchronously. Asynchronous operations are available in many .NET Core libraries and frameworks, including file I/O, network I/O, and database access.

Here's an example of an asynchronous operation that performs a network request using the HttpClient class:

string url = "https://www.microsoft.com";
string contents = await DownloadPageContents(url);
Console.WriteLine(contents);
Console.ReadLine();

async Task<string> DownloadPageContents(string url)
{
    using (HttpClient client = new HttpClient())
    {
        var response = await client.GetAsync(url);
        return await response.Content.ReadAsStringAsync();
    }
}

The GetAsync() method performs the network request asynchronously and returns a Task<HttpResponseMessage> object. The await keyword is used to wait for the completion of the network request before reading the response content using the ReadAsStringAsync() method, which also performs asynchronously.

Asynchronous programming is particularly useful in applications that perform I/O-bound operations, such as accessing files or network resources, where the time spent waiting for I/O operations to complete can be used to perform other tasks. In contrast, synchronous programming blocks the execution thread until the operation is completed, which can be inefficient and unresponsive.

Hope this article helps you to understand what Asynchronous programming is and how you can perform in .NET Core using Async and Await keywords.

No comments:

Powered by Blogger.