Tuesday, April 25, 2023

When and How to use 'async' and 'await' in C# ?

In C#, the 'async' and 'await' keywords are used to write asynchronous code that is easier to read, write, and maintain. Here's how and when to use them.

1. Define an 'async' method: 
        To define an 'async' method, you need to mark it with the 'async' keyword. This tells the compiler that this method is going to contain asynchronous operations.
public async Task GetDataAsync()
{
    // Perform some asynchronous operation here
}
2. Use the 'await' keyword: 
        Inside an 'async' method, you can use the 'await' keyword to asynchronously wait for an operation to complete. This makes the code look more synchronous and easier to read.
public async Task GetDataAsync()
{
    HttpClient httpClient = new HttpClient();
    HttpResponseMessage response = await httpClient.GetAsync("https://example.com");
    string result = await response.Content.ReadAsStringAsync();
    return result;
}
In the above example, 'httpClient.GetAsync()' and 'response.Content.ReadAsStringAsync()' are both asynchronous methods that return a 'Task'. The 'await' keyword tells the compiler to wait for these methods to complete asynchronously, without blocking the main thread.

3. Return a 'Task' or 'Task': 
        An 'async' method should always return a 'Task' or 'Task' so that the caller can await the method's completion.
public async Task GetDataAsync()
{
    HttpClient httpClient = new HttpClient();
    HttpResponseMessage response = await httpClient.GetAsync("https://example.com");
    string result = await response.Content.ReadAsStringAsync();
    return result;
}
In the above example, 'GetDataAsync()' returns a 'Task'. The caller can then use the 'await' keyword to asynchronously wait for the method to complete and get the result.

To summarize, use 'async' and 'await' when you need to write code that performs long-running or I/O-bound operations, without blocking the main thread. This makes your code more responsive and easier to maintain.

No comments:

Post a Comment