How to use async and await in C# to achieve asynchronous operations?
In C#, you can utilize the async and await keywords to achieve asynchronous operations. Here’s a simple example:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
await DoAsyncOperation();
}
static async Task DoAsyncOperation()
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}
In the example above, both the Main method and DoAsyncOperation method are marked with the async keyword, indicating that they are asynchronous methods. In the DoAsyncOperation method, the await keyword is used to wait for asynchronous operations to complete, such as sending an HTTP request and reading the response content. While the await keyword waits for the asynchronous operation to complete, the current thread is released and returned to the caller, avoiding thread blocking.