Does .ConfigureAwait(false) help executing async/await tasks in-parallel?
There are times when you want to process the next set of tasks before one is complete in a fire and forget manner and async/await is the answer to it.
Solution to this is to run the task, keep the handle with you and wait for it as you reach the end of the flow so that the main thread doesn’t run out before the task(s) in hand are completed.
What .ConfigureAwait(false) does to the execution?
ConfigureAwait(false) configures the task so that continuation after the await does not have to be run in the caller context, therefore avoiding any possible deadlocks.
I was not sure if .ConfigureAwait(false) help in parallel execution of the tasks and hence did a quick test to verify and thought of sharing it here.
This is my first post on medium by the way :-)
You can either have individual handles for each of the task and await them one by one, or you can add the handles in a list and await them all at once.
To compare and demonstrate I’ve created a sample class with one async method:
The AsyncMethods class above contains a single method - “SleepAsync” which accepts how many seconds you want it to sleep. It logs a message when it starts and completes.
In the below snippet, I’ve added three methods to test the execution flow and their the execution times.
So, in the Program class, there’s a main method and three other methods with different execution mechanism of async/await. Also, there is a Stopwatch to keep track of the elapsed time.
- Execute() run the tasks normally and awaits them individually.
- ExecuteWithConfigureAwait() run the tasks with .ConfigureAwait(false) and awaits them individually.
- ExecuteWithTaskRun() run the tasks normally and awaits them all at once.
I get the following output upon execution:
It clearly shows that the third method only, with Task.WaitAll, runs the tasks in parallel and other methods execute them one after other.
.ConfigureAwait(false) signals the UI thread to continue and the process with retur to it to next operation as soon it’s done.
So, if you have multiple methods running in parallel and you want them to run in any order, you must be looking for Task.WaitAll().
Thanks for reading, cheers!