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?
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.
The Parallel. ForEach does not understand async delegates, so the lambda is async void .
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.
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).
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With