A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

C# Tutorial 11.2: async and await keywords

 


Certainly! The async and await keywords in C# are used to simplify asynchronous programming. Asynchronous programming allows you to perform non-blocking operations, making your applications more responsive. The async keyword is used to define an asynchronous method, and the await keyword is used to indicate where the asynchronous operation should pause and wait for the result without blocking the entire thread. Here's a tutorial to help you understand and use these keywords effectively:

1. Basics of Asynchronous Programming:

1.1 Understanding Asynchronous Programming:

Asynchronous programming allows you to execute code without waiting for the result, making it suitable for tasks that might take time, such as network requests or file I/O. In traditional synchronous programming, each line of code is executed sequentially, blocking the thread until the operation is complete.

1.2 Why Use Asynchronous Programming:

  • Improved responsiveness: UI remains responsive during long-running operations.
  • Efficient resource utilization: Threads are not blocked, enabling better resource usage.
  • Scalability: Multiple asynchronous tasks can be performed concurrently.

2. Declaring and Using async Methods:

public async Task<int> MyAsyncMethod()
{
    // Asynchronous code goes here
    int result = await SomeAsyncOperation();
    return result;
}

  • The return type of an async method is typically Task or Task<T> where T is the type of the result.
  • The async modifier allows the use of await within the method.

3. Using the await Keyword:

3.1 Awaiting an Asynchronous Operation:

public async Task MyMethod()
{
    // Some synchronous code

    // Await an asynchronous operation
    int result = await MyAsyncMethod();

    // Continue with the result
    Console.WriteLine(result);

    // More code
}
  • await is used to pause the method until the awaited operation completes.
  • Control returns to the calling method while the awaited operation is in progress.

4. Handling Exceptions in Asynchronous Code:

4.1 Handling Exceptions:

public async Task<int> MyAsyncMethod()
{
    try
    {
        // Asynchronous code
        int result = await SomeAsyncOperation();
        return result;
    }
    catch (Exception ex)
    {
        // Handle exception
        Console.WriteLine($"An error occurred: {ex.Message}");
        return -1;
    }
}
  • Use try-catch blocks to handle exceptions in asynchronous code.

5. Running Multiple Asynchronous Tasks:

5.1 Running Multiple Tasks Concurrently:

public async Task RunMultipleTasks()
{
    Task<int> task1 = MyAsyncMethod();
    Task<int> task2 = AnotherAsyncMethod();

    // Wait for any of the tasks to complete
    Task<int> completedTask = await Task.WhenAny(task1, task2);

    // Continue with the completed task's result
    Console.WriteLine(completedTask.Result);
}
  • Task.WhenAny allows you to continue when any of the tasks completes.

Conclusion:

Understanding and effectively using the async and await keywords in C# can greatly improve the performance and responsiveness of your applications. Asynchronous programming is a powerful tool for handling time-consuming operations without blocking the main thread.