Asynchronous Programming is honestly very confusing for people. Is it Parallel programming? Not quite. Is it multi-threaded programming? Not quite. Asynchronous programming allows you to use a thread for other things while a different process outside of your own application is happening. Basically, instead of having your thread sit around and wait for a database call to return, we start using the thread we are on for something else and another thread (or the same thread) will continue on with the execution of your code. If you’d like to know more in-depth then we can get into details in another article. In this one we will dive into the basics of await and async and what to do and some things NOT to do.
Async Await Basics
So creating an asynchronous application in the latest versions of .net core is incredibly easy. Use a Task return type and add async onto the method call. Also, make sure you do this through EVERY layer of your code. So let’s look at basic Signature for getting a single item back from another method call:
public async Task<ReturnObject> GetReturnObjectById(long id){
return await this.dbcontext.MyData.FirstOrDefaultAsync(x => x.id == id);
}
Now this if very very simplistic with a ReturnObject type being returned from the MyData table in a dbcontext while matching with the first item that matches the id I pass in.
Let’s look at a few different scenarios.
- Task.WaitAll
- Task.WhenAll
- .Result
So these items listed above work quite differently while in the asynchronous programming spectrum. Only one of them should really ever be used - the Task.WhenAll. The rest of the items are technically blocking calls unless you do something specific beforehand to identify that you do not want to wait and that you want to just come back when the asynchronous call is finished. From previous experiences .Result is the worst offender amongst all of these items and is misused way too much. in our previous example we can see how to use .Result to get a result value:
public async Task<ReturnObject> GetReturnObjectById(long id){
return this.dbcontext.MyData.FirstOrDefaultAsync(x => x.id == id).Result; //DO NOT DO THIS!
}
So, in this example we inserted a .Result and removed the await. We still compile but what we have effectively done is lock our thread down to spin and wait until the Result actually comes back. This is NOT good. Please don’t do this.
public async Task<ReturnObject> GetReturnObjectById(long id){
var taskList = new List<Task<ReturnObject>>();
var getTask = this.dbcontext.MyData.FirstOrDefaultAsync(x => x.id == id);
taskList.Add(getTask);
await Task.WaitAll(taskList); //DON'T DO THIS!
return taskList.FirstOrDefault().Result;
}
Ok, so now we are getting a little bit more complicated. This is a pattern for doing multiple asynchronous tasks in parallel. Our code has one major issue in it though - the Task.WaitAll.
public async Task<ReturnObject> GetReturnObjectById(long id){
var taskList = new List<Task<ReturnObject>>();
var getTask = this.dbcontext.MyData.FirstOrDefaultAsync(x => x.id == id);
taskList.Add(getTask);
await Task.WhenAll(taskList); //Non-blocking
return taskList.FirstOrDefault().Result;
}
Here we have converted the Task.WaitAll to Task.WhenAll. What this does is that we convert the blocking call into a non-blocking call. All threads fire off and return back. We do not block the individual thread that has the Task.WhenAll in it. Task.WaitAll, however, will block the thread until ALL threads return in some completed state.
But in this instance we are still calling .Result which contradicts what I said earlier in the article. In this use case the task has already ran to completion during the WhenAll that we did an await on. This means that the .Result is already available for us to use in this circumstance and will not block the thread execution while the remote execution is done off thread.
In short there are a few simple rules to follow:
- Use Await and Async
- Always try to to have a return type of a Task
- Avoid .Result
- Avoid Task.WaitAll
These simple rules should help your out on your journey towards asynchronous programming. I’ve spent a lot of time tracking down .Result because a developer thoguht they knew what they were doing when in fact they were simply in the dark about how await and async work. If you abide by these simple rules as a baseline you should be able to see a performance gain as your individual threads are free up to do useful work rather than waiting around for other work to be completed.