In this tutorial, our aim is to understand and implement asynchronous methods in C#. Asynchronous programming is essential for improving the efficiency of your applications, as it allows multiple operations to run concurrently. By the end of this tutorial, you will be able to write methods that execute long-running operations asynchronously and return a Task
or Task<T>
to signify the ongoing operation.
Basic understanding of C# programming is required. Some familiarity with Tasks and threading would be beneficial but is not necessary.
Async functions allow you to write asynchronous code in a way that looks synchronous, which can make your code much easier to read and understand. In C#, we use the async
keyword to declare an asynchronous method.
A method declared as async
returns a Task
or Task<T>
. Task
is used if no value is returned and Task<T>
is used if a value is returned.
Use the async
and await
keywords in the method signature to clearly identify the method as asynchronous. This helps with readability and maintainability.
public async Task SimpleAsyncMethod()
{
// This line will run asynchronously
await Task.Delay(5000);
Console.WriteLine("Hello, World!");
}
In this example, Task.Delay(5000)
is a placeholder for a potentially time-consuming operation. It simply delays the continuation of the method by 5 seconds. The await
keyword tells the compiler that the method can't continue past this point until the awaited task is complete.
Expected output (after 5 seconds): Hello, World!
public async Task<int> CalculateSumAsync()
{
await Task.Delay(5000);
int sum = 5 + 5;
return sum;
}
In this example, the method returns a Task<int>
, which means it's an async method that returns an integer. After a delay of 5 seconds, the method calculates the sum of 5 and 5, and then returns it.
Expected output (after 5 seconds): 10
In this tutorial, you have learned about asynchronous programming in C# and how to implement async methods. You've also seen how to return values from async methods.
For further reading, I recommend looking at the official Microsoft documentation on async programming in C#.
Write an async method that waits for 2 seconds and then prints Hello, World!
. Run this method multiple times concurrently to see the effect of asynchronous programming.
Write an async method that waits for a random amount of time between 1 and 5 seconds, then returns the amount of time it waited.
Here are the solutions for the exercises:
public async Task HelloWorldAsync()
{
await Task.Delay(2000);
Console.WriteLine("Hello, World!");
}
You can run this method multiple times concurrently using Task.WhenAll()
.
public async Task<int> RandomDelayAsync()
{
Random rnd = new Random();
int delay = rnd.Next(1, 6) * 1000;
await Task.Delay(delay);
return delay;
}
This method generates a random number between 1 and 5, multiplies it by 1000 to get a delay in milliseconds, waits for the specified delay, and then returns the delay.