Speeding Up C# Async Code
Let’s keep this short and sweet.
Suppose we have a controller that gathers some data for us from 3 different endpoints that we can call.
Something like:
async Task Main()
{
var impressions = await _controller.GetImpressions();
var clicks = await _controller.GetClicks();
var conversions = await _controller.GetConversions();
}
In this example let’s say that each of these calls takes a simulated 1 second to go to that controller, gather that data and return it.
3 seconds might not seem so bad, and maybe that’s acceptable but we can cut that time wayyy down with relative ease.
Let’s convert each of these to tasks, and await them all in parallel all at once.
async Task Main()
{
var impressionsTask = _controller.GetImpressions();
var clicksTask = _controller.GetClicks();
var conversionsTask = _controller.GetConversions();
await Task.WhenAll(impressionTask, clicksTask, conversionsTask);
}
Writing your code this way will take this simulated 3 seconds from above and drop it down to 1 second or less of waiting time while all these run in parallel.
To access the results you can do this:
async Task Main()
{
var impressions = impressionTask.Result;
var clicks = clickTask.Result;
var conversions = conversionsTask.Result;
}
There is a slight drawback to this approach, if your calls are prone to errors you will only get the first error back from the results, not an aggregated list of errors.
Well… there you have it, a simple change in your code to reap some gains in performance time.
Await the tasks all at once!
Thanks,
-Cory