top of page

Asynchronous programming in C#

Updated: Feb 23, 2023

The primary mechanism for asynchronous programming in C# is through the use of the async and await keywords. These keywords allow developers to define asynchronous methods that can be called from a main program loop without blocking the main thread. In this article, we will discuss Asynchronous programming in C#.


Asynchronous programming in C# allows developers to write code that runs concurrently, allowing long-running tasks to execute without blocking the main thread. This can result in improved performance and responsiveness of the application.


What is asynchronous programming?

Asynchronous programming is an effective way to reduce the delay or wait time that is happening in the code. It avoids the following scenario — an activity is blocked in a synchronous process, which will in turn block the entire application by blocking the other tasks from executing.


Keywords async and await are used in C# for achieving asynchronous programming. To make a function asynchronous, the async keyword will be added in front of the method name. Below is an example of the syntax of an asynchronous method.

public async Task DoWork(){ }


When you should use asynchronous programming?

Asynchronous programming should be used when you need to perform long-running operations that would otherwise block the main thread, such as I/O-bound tasks, network communication, or CPU-bound tasks that can be broken down into smaller pieces.


Here are some scenarios where using async programming in C# can be beneficial:

  1. I/O-bound tasks: Tasks that involve reading or writing to a file, accessing a database, or calling a web API can take a long time to complete, and can block the main thread if performed synchronously. By using async programming, you can perform these tasks asynchronously without blocking the main thread, allowing the application to remain responsive.

  2. Network communication: When communicating with a remote server over a network, latency can be a major bottleneck that can slow down the application. By using async programming, you can send and receive data asynchronously, allowing the application to continue executing other tasks while waiting for the network communication to complete.

  3. CPU-bound tasks: While async programming is primarily used for I/O-bound tasks, it can also be beneficial for CPU-bound tasks that can be broken down into smaller pieces. By breaking up the task into smaller pieces and using async programming, you can execute each piece concurrently, reducing the overall execution time and improving performance.

Overall, async programming in C# should be used when you need to perform long-running operations without blocking the main thread. By using async programming, you can improve the responsiveness and performance of your application, making it more efficient and scalable.


How to implement asynchronous programming in C#

Here are some basic steps to implement asynchronous programming in C#:


STEP 1: Define an asynchronous method: The first step in asynchronous programming is to define an asynchronous method that performs a long-running operation. This method should return a Task or Task<T> object to indicate its status.


STEP 2: Add the async keyword: To indicate that the method is asynchronous, add the async keyword to the method signature.


STEP 3: Use the await keyword: Inside the asynchronous method, use the await keyword to call other asynchronous methods or perform I/O operations without blocking the main thread.


STEP 4: Call the asynchronous method: In the main program loop, call the asynchronous method using the await keyword to indicate that the method should be executed asynchronously.


Here's an example of an asynchronous method in C#:

public async Task<int> LongRunningOperationAsync()
{
    // Perform a long-running operation asynchronouslyawait Task.Delay(5000);
    return 42;
}

In this example, we define an asynchronous method called LongRunningOperationAsync() that returns an integer after performing a long-running operation asynchronously. The await keyword is used to call the Task.Delay() method, which simulates a long-running operation by delaying execution for 5 seconds.


Here's how we would call this method asynchronously from a main program loop:

public async Task RunProgramAsync()
{
    Console.WriteLine("Starting program");

    int result = await LongRunningOperationAsync();

    Console.WriteLine($"The result is {result}");
}

public static void Main(string[] args)
{
    RunProgramAsync().Wait();
}

In this example, we define a method called RunProgramAsync() that calls the LongRunningOperationAsync() method using the await keyword. We then call RunProgramAsync() from the main program loop using the Wait() method to indicate that we want to wait for the asynchronous operation to complete before exiting the program.


Conclusion

Asynchronous programming in C# is easy to achieve using the async and await keyword. It provides the advantage of executing the long-running and independent methods in a separate thread as that of the main thread. It improves the responsiveness of the application which thereby increases customer satisfaction.

0 comments

Comments


bottom of page