Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most elegant way to load multiple variables asynchronously in parallel in c#

Tags:

c#

async-await

This is best illustrated with an example.

Say I want to load several records from a database at the beginning of a web request. I want to pull in all the necessary data asynchronously. I might have something like this:

var user = await Database.GetUser(userId);
var group = await Database.GetGroup(groupId);
var members = await Database.GetGroupMembers(groupId);

Now let’s say I want to load this data in parallel. Suddenly this nice clear/clean async code becomes a bit messy.

var userTask = Database.GetUser(userId);
var groupTask = Database.GetGroup(groupId);
var membersTask = Database.GetGroupMembers(groupId);

await Task.WhenAll(userTask, groupTask, membersTask);

var user = userTask.Result;
var group = groupTask.Result;
var members = membersTask.Result;

Is there a nicer, more succinct way to achieve this?

like image 459
stuart Avatar asked Sep 15 '17 08:09

stuart


People also ask

Does async await run in parallel?

You can call multiple asynchronous functions without awaiting them. This will execute them in parallel. While doing so, save the returned promises in variables, and await them at some point either individually or using Promise.

Can we use async in parallel ForEach?

The Parallel. ForEach does not understand async delegates, so the lambda is async void .

How do I run two tasks in parallel?

If you have several tasks that can be run in parallel, but still need to wait for all the tasks to end, you can easily achieve this using the Task. WhenAll() method in . NET Core. This will upload the first file, then the next file.

How do I use multiple async await?

In order to run multiple async/await calls in parallel, all we need to do is add the calls to an array, and then pass that array as an argument to Promise. all() . Promise. all() will wait for all the provided async calls to be resolved before it carries on(see Conclusion for caveat).


1 Answers

Separate the task start and the await:

var userTask = Database.GetUser(userId);
var groupTask = Database.GetGroup(groupId);
var membersTask = Database.GetGroupMembers(groupId);

var user = await userTask;
var group = await groupTask;
var members = await membersTask;
like image 88
Ry- Avatar answered Oct 18 '22 23:10

Ry-