C# Keywords Tutorial – Part 5: async
Amr Saafan
Founder | CTO | Software Architect & Consultant | Engineering Manager | Project Manager | Product Owner | +27K Followers | Now Hiring!
The async keyword in the robust computer language C# enables programmers to write asynchronous code. The timeliness and scalability of systems that need lengthy activities, like I/O operations or database queries, are improved by using asynchronous programming. We will discuss the async keyword in C# and give usage examples in this blog article.
What is the async keyword in C#?
In C#, asynchronous methods are defined with the async keyword. By allowing the method to run in a different thread, an asynchronous method enables the calling thread to carry on with its work without waiting for the method to finish. Long-running tasks like database queries or I/O activities that would otherwise block the main thread can benefit from asynchronous methods.
Syntax of the async keyword
The syntax for using the?async?keyword in C# is as follows:
async Task MethodNameAsync()
{
? ? // Asynchronous code here
}
In this syntax,?MethodNameAsync()?is the name of the asynchronous method, and?Task?is the return type of the method. The?async?keyword indicates that the method is asynchronous, and the?await?keyword is used to wait for the completion of asynchronous operations.
Examples of using the async keyword in C#
Let’s take a look at some examples of how the?async?keyword can be used in C#.
领英推荐
Example 1: Downloading a file asynchronously
In this example, we have a method that downloads a file from a remote server asynchronously. The?HttpClient?class is used to download the file, and the?async?and?await?keywords are used to ensure that the method does not block the main thread.
async Task DownloadFileAsync(string url)
{
? ? using (var client = new HttpClient())
? ? {
? ? ? ? var response = await client.GetAsync(url);
? ? ? ? var content = await response.Content.ReadAsStringAsync();
? ? ? ? // Process the downloaded content
? ? }
}
Example 2: Performing a long-running database query asynchronously
In this example, we have a method that performs a long-running database query asynchronously. The?SqlConnection?and?SqlCommand?classes are used to execute the query, and the?async?and?await?keywords are used to ensure that the method does not block the main thread.
async Task<List<Customer>> GetCustomersAsync()
{
? ? var customers = new List<Customer>();
? ? using (var connection = new SqlConnection(connectionString))
? ? {
? ? ? ? await connection.OpenAsync();
? ? ? ? using (var command = new SqlCommand("SELECT * FROM Customers", connection))
? ? ? ? {
? ? ? ? ? ? var reader = await command.ExecuteReaderAsync();
? ? ? ? ? ? while (await reader.ReadAsync())
? ? ? ? ? ? {
? ? ? ? ? ? ? ? var customer = new Customer
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? Id = reader.GetInt32(0),
? ? ? ? ? ? ? ? ? ? Name = reader.GetString(1),
? ? ? ? ? ? ? ? ? ? Email = reader.GetString(2)
? ? ? ? ? ? ? ? };
? ? ? ? ? ? ? ? customers.Add(customer);
? ? ? ? ? ? }
? ? ? ? }
? ? }
? ? return customers;
}
Example 3: Processing a collection of items asynchronously
In this example, we have a method that processes a collection of items asynchronously. The?Parallel.ForEach?method is used to process the items in parallel, and the?async?and?await?keywords are used to ensure that the processing does not block the main thread.
async Task ProcessItemsAsync(List<Item> items)
{
? ? await Task.Run(() =>
? ? {
? ? ? ? Parallel.ForEach(items, async item =>
? ? ? ? {
? ? ? ? ? ? await ProcessItemAsync(item);
? ? ? ? });
? ? });
}
async Task ProcessItemAsync(Item item)
{
? ? // Asynchronous processing here
}