Async and Await in C#

Posted by

Async and Await are two keywords in C# that make it easier to write asynchronous code. They are used to write asynchronous methods that can run in the background, without blocking the main thread, and without causing the application to become unresponsive.

Here is a step-by-step tutorial on how to use Async and Await in C#:

  1. Marking a Method as Async: To make a method asynchronous, you need to add the keyword “async” before the return type of the method.
public async Task MyMethod()
{
   // code here
}

2. Awaiting a Task: The await keyword is used to wait for an asynchronous operation to complete. It is used to wait for a Task to complete, which is represented by an instance of the Task class.

public async Task MyMethod()
{
   await Task.Delay(1000);
}

3. Returning a Value from an Async Method: You can use the Task<TResult> class to return a value from an asynchronous method.

public async Task<int> GetData()
{
   await Task.Delay(1000);
   return 5;
}

4. Exception Handling in Async Methods: You can handle exceptions in asynchronous methods just like you would in synchronous methods.

public async Task MyMethod()
{
   try
   {
      await Task.Delay(1000);
   }
   catch (Exception ex)
   {
      Console.WriteLine(ex.Message);
   }
}

5. Combining Multiple Async Tasks: You can use the await keyword to wait for multiple asynchronous operations to complete.

public async Task MyMethod()
{
   Task task1 = Task.Delay(1000);
   Task task2 = Task.Delay(2000);
   await Task.WhenAll(task1, task2);
}

That’s it! You now know the basics of using Async and Await in C#. Async and Await make it easier to write asynchronous code, and they help you to write more efficient, responsive, and scalable applications.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.