What is Asynchronous Programming?
Asynchronous programming is writing code that allows several things to happen at the same time without
"blocking", or waiting for other things to complete. This is different from synchronous programming, in which
everything happens in the order it is written (if you write code for a living, chances are it will be synchronous code).
Let's look at a synchronous C# method:
public string GetNameAndContent()
{
var name = GetLongRunningName(); //Calls another webservice, can take up to 1 minute.
var content = GetContent(); //Takes up to 30 seconds
return name + ": " + content;
}
Every time something calls this method, the caller has to wait up to 1 minute before it can resume processing. That's
a minute of wasted time, time it could be spending doing other tasks.
With .NET asynchronous programming, we can modify this method like so:
public async Task<string> GetNameAndContent()
{
var nameTask = GetLongRunningName(); //This method is asynchronous
var content = GetContent(); //This method is synchronous
var name = await nameTask;
return name + ": " + content;
}
We made three changes to the method:
1. We marked the method as async. This tells the compiler that this method can run asynchronously.
2. We used the await keyword on the nameTask variable. This tells the compiler that we will ultimately need the
result of the GetLongRunningName() method, but we don't need to block on that call.
3. We changed the return type to Task<string>. This informs the caller method that the return type will
eventually be string, but not right away and that can do other things while GetLongRunningName() is processing.
But even this wasn't obvious to me. What were we actually doing when "waiting" for GetLongRunningName() to
finish?
This is the difficult part to put in simple terms, but I'll try anyway. Essentially, the system wants to
execute GetLongRunningName() because it was called first, but because it is an async task and we are awaiting it,
control is relinquished to fire GetContent(), which means we now have the work for two methods running at the
same time. What this does not do is spin up another thread; using async and await do not cause threads to be
created.