Asynchronous programming in C#

28 december 2020 om 10:00 by ParTech Media - Post a comment

Imagine a soft drinks manufacturing company that typically bottles the drink and sells it in the market. Even though the final product of this company is a soft drink, the process of manufacturing can be divided into two subprocesses. One where the bottles are getting manufactured and another where the drinks are getting manufactured. When both these products are ready, the drink is filled in the bottle, sealed, and packed.

If you notice here, the manufacturing of the bottles and drink were not interdependent. Both the manufacturing processes were happening in parallel in such a way that neither the drink nor the bottle had to wait for the completion of the other product.

Let us now look at an example in the software industry. There is a certificate validation website, which accepts as many as 10 certificates at a time. It provides the authenticity of these certificates by validating them against the corresponding issuing authority. Suppose in this workflow, the application takes one certificate at a time, validates it, and then picks the next certificate, the amount of time the user will be waiting for this to get completed will be very high. This, in turn, will reduce the incoming users to the website. But, imagine if the website can get the input of all the 10 certificates and validate it simultaneously so that the user doesn't need to wait for a longer time. Will this be not an encouraging factor for the user to visit again and again to validate more and more things? The validation process is after all much quicker. That is the advantage of doing things asynchronously.

In this blog, we are going to understand what is asynchronous programming and how to achieve it in C#.

Table of contents

  1. What is asynchronous programming?
  2. When to use asynchronous programming
  3. Return types of an asynchronous program
  4. Implementing asynchronous programming in C#
  5. Key concepts of asynchronous programming
  6. Conclusion

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 to use asynchronous programming?

Whenever there is a blocking code that is independent of the remaining process in the code execution, then asynchronous programming can be implemented.

On executing a particular method asynchronously, it gets executed in a separate thread and not in the main thread. Also, for long-running tasks, asynchronous programming can be implemented to make the main thread free.

Asynchronous programming can be implemented in the below areas:

  1. File read/write operations that are independent of the main activity of the application.
  2. Third-party API calls
  3. Loading of maps or special plugins that needs to be loaded in the application other than the main content.
  4. Code logics that are independent of the main operation. Example - Logging that a user has signed in and browsing this product while product details are still pulled in the main thread and displayed to the user.

Return types of an asynchronous program

Let's now see the different return types that the async methods support -

void - if void has been mentioned as the return type for an async method, then the method is not awaitable. In that case, the method is called the ‘fire and forget’ method, where the execution of the async method happens in parallel in a separate thread other than the main thread.

Task - To make a method awaitable, the return type of the method has to be made as a task so that it doesn't return any data to the calling method.

Task T - To make a method awaitable and return any type of data, task T can be used.

Implementing asynchronous programming in C#

In this section, let's see in detail how to implement asynchronous programming in C#.

Step 1

Create a .Net-based Console application and provide a valid name for the project.

Step 2

Once the project is created, the solution will have the below files.

Step 3

Open the Program.cs file and update the code to have two methods; each method will have a loop. Let's say, the first method has a loop of 20 iterations and the second method has a loop of 10 iterations.

Step 4

After updating the code, let's run the code in the synchronous mode and observe the results.

You can notice that method 1 was first completely executed and later method 2 was executed. Here both method 1 and method 2 were not interdependent, but still, method 2 had to wait until method 1 was completely executed.

Now let's implement asynchronous programming for method 1 and observe how it impacts the result.

Step 5

To implement asynchronous programming, let's add async Task to method1 header. And inside the method, add the code as shown in the below image.

After adding the code, let's run the application. Take a look at the results tab. You will notice that initially, method1 got executed, but later method 2 also started to get executed in the middle without waiting for method 1 to get completed. In short, both the methods were running asynchronously without waiting for each other.

Key concepts of asynchronous programming

Now that we have seen how to implement asynchronous programming in C#. Let's understand some key concepts in implementing it -

  1. Asynchronous methods should be called using the await keyword, else they will be running synchronously.
  2. Method input parameters cannot be declared as async.
  3. The main method cannot be declared as asynchronous and the await key cannot be used inside it.
  4. In a try/catch/finally block, asynchronous calls can be made only inside the try block.

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.

Nieuwste