c sharp

How to Use Async and Await in C#

Async and Await are powerful methods in C# that allow you to perform time-consuming operations without blocking the main thread. One of the key functions of C# that supports asynchronous programming is the async() and await(). This article, will explain what async and await are, and how they are used in C# programming.

What is Async in C#

The async() method runs synchronously till it reaches its first await expression. The async() is used before the return type of the method, and the method signature must return a Task or Task<T> object, where T is the type of the value that the method returns.

async <returnType> <methodName>(<parameters>)

{

  // Asynchronously wait for some operation to complete

  // Return a Task or Task<T> object

}

Here are the changeables in the syntax:

  • <return_type>: The return type of the method, this can be any valid C# data type.
  • <method_name>: The name of the method.
  • <parameters>: The method parameters. These can be any valid C# data types.

What is Await in C#

The await() is used to pause the execution of the method until the asynchronous operation completes, here is the syntax for this function:

await <async_method_call>

Here are the changeables in the syntax:

  • <result_type>: The type of the result that the asynchronous operation returns.
  • <result_variable>: The variable which stores the result of the asynchronous operation.
  • <async_method_call>: The method call that performs the asynchronous operation.

How to use Async and Await in C#

Using async and await, you can create code that is more responsive and efficient, as it frees up the main thread to handle other operations while the asynchronous operations are running in the background. Below is the example code that uses both async and await and demonstrates how to use async and await to perform non-blocking, asynchronous operations in C#.

using System;

using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
Console.WriteLine("Start calculating");

        // Start a task to add 2 and 3 asynchronously
        Task task1 = AddAsync(2, 3);
Console.WriteLine("Adding...");

        // Start a task to subtract 5 from 10 asynchronously
        Task task2 = SubtractAsync(10, 5);
Console.WriteLine("Subtracting...");

        // Wait for the first task to complete and get the result
        int result1 = task1.Result;
Console.WriteLine($"2 + 3 = {result1}");

        // Wait for the second task to complete and get the result
        int result2 = task2.Result;
Console.WriteLine($"10 - 5 = {result2}");

Console.WriteLine("Calculation complete!");
    }

    // A method that adds two numbers asynchronously
    static async TaskAddAsync(int a, int b)
    {
        await Task.Delay(1000); // simulate some delay
        return a + b;
    }

    // A method that subtracts two numbers asynchronously
    static async TaskSubtractAsync(int a, int b)
    {
        await Task.Delay(1000); // simulate some delay
        return a - b;
    }
}

In the code, the AddAsync and SubtractAsync methods use the await keyword to indicate that they are performing an asynchronous operation, which in this case is a simulated delay using this task delay() function. This allows the methods to return immediately without blocking the main thread.

In the Main method, the AddAsync and SubtractAsync methods are called using the await keyword to asynchronously wait for the results of the operations. This allows the program to continue running and perform other tasks while waiting for the asynchronous operations to complete.

Once the tasks are complete, the Result property is used to retrieve the result of each task, and print to the console. Here is the output of the code that we discussed earlier that performs addition and subtraction using async and await:

Conclusion

Asynchronous programming can provide several benefits for your application, including improved performance, increased responsiveness, and simplified code. By using asynchronous programming techniques, you can create more efficient and responsive applications in C#. The async keyword is used with the function name to make it work asynchronously while await will suspend the operation until the asynchronous method finishes execution and prints the result.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.