Site icon

Async and await in C#

C# introduced the async and await keywords as part of the .NET Framework 4.5 to simplify asynchronous programming. These keywords allow us to write asynchronous code, making it more readable, maintainable.

In this blog post, we’ll explore more about the async and await and their usage.

How to use async and await keywords in C#?

In C# , we can use async and await keywords to mark a method to behave asynchronously, which allows it to operate in the background while other main process runs as usual.

Below steps allows a method to operate asynchronously.

How does async work in C#?

Async Await in C# Example 

Let’s take a simple example to understand the usage of async and await in C#: Please copy attached dummy file Sample.txt in C:\Temp folder before executing this example.

In this example:

It will generate below output upon successful execution.

Async_Await_File_Read_Sample_1

If you look at the output, the control didn’t stop at the line string fileData = await ReadFileDataAsync(filePath); and the main thread keep on printing the output on the console and once it received the fileData then it printed that on the console.

This example demonstrates how to use async and await to perform file reading operations asynchronously, allowing the application to remain responsive while reading the file’s content.

Implementation of Async and Await in C#:

1) Asynchronous Parallel Execution:

In the above example, the Main method starts two tasks using Task.Run to print “Task 1” and “Task 2”. It then awaits the completion of both tasks using Task.WhenAll and prints “Parallel execution completed!” to the console.

2) Asynchronous Data Processing with Parallel.ForEach :

The output will be the processed data, where each number from the list is multiplied by 2. If an error occurs, the catch block will be triggered, and the error message will be displayed.

3) Chaining Asynchronous Tasks using Async and Await:

The output will be the result of multiplying the sum of 2 and 3 by 4. If an error occurs, the catch block will be triggered, and the error message will be displayed.

Key points of using async & await

Conclusion:

Asynchronous programming using the async and await pattern in C# is a powerful technique to improve the responsiveness and efficiency of applications. By leveraging async and await, developers can write code that remains responsive, utilizes system resources efficiently, and delivers a better user experience.

Exit mobile version