If you get one thing from this article, it should be that the method pauses and not the thread.
Let’s look into it a bit further - in our day to day jobs, the code we all write makes web API requests and waits for the response, or our data access layer queries a database and once again waits for a response.
And there are many other scenarios like the ones I just described. The main question then becomes what does the thread do while the code is sitting and waiting for a response to arrive or for a file to finish loading?
Now wouldn’t it be great if you could do something else WHILE waiting for that other task to finish executing? As you can imagine, you would be able to get a lot more things done.
Well, luckily there is a way to do that in C# and the way you do that is by using async and await keywords. Let’s look at a more specific example below:
The problem
Imagine a simple method that takes a cryptocurrency symbol, such as BTC for Bitcoin, fetches its current price from a web API and returns it as a decimal:
class CryptoPriceService(HttpClient client)
{
public decimal GetPrice(string coin)
{
string text = client.GetStringAsync($"https://api.example.com/crypto/{coin}/price").Result;
return decimal.Parse(text);
}
}
This works, but because .Result blocks the thread until the HTTP call has completed, the thread has to sit around and do nothing for the entire duration of the HTTP call. Now in a desktop app there is one UI thread which draws things on the window - this is how you see the buttons and input boxes and other components. And it also runs code behind commands which are controlling the user interface.
So if one of those functions happens to call this method above then the UI thread would be blocked and the screen would look frozen. And in an ASP.NET Core app, this thread could have been serving another request instead of waiting, so as a result it would handle fewer users.
How async and await work
The main idea is very simple as mentioned above - await pauses the method, not the thread.
When execution reaches the await keyword on a task that hasn’t finished yet, the method pauses at that point and moves the control back to its caller. Now the thread is free to do other work. When the task completes, the method simply picks up right after the await, with the result ready to be used.
Nothing sits blocked, doing nothing, while the HTTP call or something else is being processed. That’s the whole trick, and it’s why async code scales so well for I/O work such as network calls, databases and files.
Writing an async method
Here is the same price lookup code, but now written to use async and await keywords. Now, the thread no longer gets blocked while the HTTP call is in progress.
class CryptoPriceService(HttpClient client)
{
public async Task<decimal> GetPriceAsync(string coin)
{
string text = await client.GetStringAsync($"https://api.example.com/crypto/{coin}/price");
return decimal.Parse(text);
}
}
Compared to the first version, three things changed in the method itself:
- It is marked with the
asyncmodifier, which is what allows theawaitkeyword within it. - It returns
Task<decimal>instead ofdecimal. You stillreturna plaindecimal, and C# wraps it in theTaskfor you. A method that returns nothing usesTaskinstead. - Its name ends with Async, so callers know it should be awaited.
Calling it reads just like synchronous code:
CryptoPriceService cryptoPriceService = new(new HttpClient());
decimal price = await cryptoPriceService.GetPriceAsync("BTC");
Running independent calls together
Now let’s look at a bit more advanced example. Say you need prices for several cryptocurrencies. The obvious thing to do is to have a foreach loop that awaits them one at a time:
string[] coins = ["BTC", "ETH", "SOL"];
foreach (string coin in coins)
{
decimal price = await cryptoPriceService.GetPriceAsync(coin);
Console.WriteLine($"{coin}: {price}");
}
In the above, each call starts only after the previous one finishes. In other words, if each call takes one second, then the above code takes three. But the thing is that the calls don’t depend on each other, so there’s no reason to wait for one to finish before starting the next.
Instead, there is another tool we can use called Task.WhenAll. So you start all of them first, then await them together with Task.WhenAll. Let’s see how that works:
Task<decimal>[] tasks = [.. coins.Select(coin => cryptoPriceService.GetPriceAsync(coin))];
decimal[] prices = await Task.WhenAll(tasks);
As you can see, you start every request, then wait for all of them at once. Now the total time is roughly that of the slowest call, which is about one second instead of three seconds like before.
It’s also important to note that prices holds the results in the same order as coins.
Cancelling work you no longer need
Now there are times when a call takes too long, or the user navigates away. These things happen and there needs to be a way to handle these cases. Most built-in async methods accept what is known as a CancellationToken, so you can pass one through your own method as well:
class CryptoPriceService(HttpClient client)
{
public async Task<decimal> GetPriceAsync(string coin, CancellationToken cancellationToken = default)
{
string text = await client.GetStringAsync($"https://api.example.com/crypto/{coin}/price", cancellationToken);
return decimal.Parse(text);
}
}
Then, the caller simply decides when to give up, for example after two seconds of making the call:
using CancellationTokenSource timeout = new(TimeSpan.FromSeconds(2));
try
{
decimal price = await cryptoPriceService.GetPriceAsync("BTC", timeout.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("The crypto price service took too long");
}
Quick note: In ASP.NET Core, you rarely ever create the token yourself. Instead, add a CancellationToken parameter to your endpoint and the framework cancels it when the client disconnects.
Common mistakes
Lastly, let’s go over some common mistakes so you don’t waste time dealing with them:
Blocking on a task. .Result and .Wait() bring back exactly the problem async was meant to solve, and in some apps they can cause a deadlock. So be careful!
decimal blocking = cryptoPriceService.GetPriceAsync("BTC").Result;
decimal nonblocking = await cryptoPriceService.GetPriceAsync("BTC");
Forgetting to await. If you call an async method without awaiting it, your code carries on before it finishes, and any exception it throws is basically lost. The compiler warns you about it, so definitely pay close attention to it!
cryptoPriceService.GetPriceAsync("BTC"); // warning that this call is not awaited!
Using async void. Callers can’t await an async void method, so an exception inside it can crash the app. In other words, if your method doesn’t return anything, return Task instead of void. Event handlers are the one exception, because their signature requires void, but that’s about it.
Stopping halfway. Once a method awaits something, its callers should be async too. In other words, don’t mix blocking calls with non-blocking calls, because it undoes all of the mentioned benefits. This is often summed up as “async all the way”.
The takeaway
Async and await don’t make the work itself faster. They stop your threads from doing nothing when they could be doing other work. Use them for anything that waits on I/O, return Task or Task<T>, start independent calls before awaiting them with Task.WhenAll, and never block on a task with .Result or .Wait(). This way you will build apps that are responsive, with no UI freezes, and servers that handle more requests with the same hardware.