I am trying to asynchronize my original code
for(var item in items)
{
dbAccess.Save(item);
}
which works fine:
var tasks = new List<Task>();
for(var item in items)
{
tasks.Add(dbAccess.SaveAsync(item));
}
await Task.WhenAll(tasks);
However, I need to add an additional clean-up call before I save and item to my DB:
var tasks = new List<Task>();
for(var item in items)
{
tasks.Add(dbAccess.DeleteAsync(item.id));
tasks.Add(dbAccess.SaveAsync(item));
}
await Task.WhenAll(tasks);
This code above is incorrect since SaveAsync should not be executed until the corresponding DeleteAsync is finished. In other words Deletion must always go before Saving for each item but the order for the items does not matter.
Is there a perfect way to do this ?
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).
WhenAll() method in . NET Core. This will upload the first file, then the next file. There is no parallelism here, as the “async Task” does not automatically make something run in in parallel.
In . NET, Task. Run is used to asynchronously execute CPU-bound code. Let's say there is a method which does some CPU-bound work. Example : looping through a large array and doing some complex computation on each element of the array.
Create an async
method that performs the delete, then the save, for a single item, and perform all of those composite operations on each item in parallel:
var tasks = items.Select(async item =>
{
await dbAccess.DeleteAsync(item.id);
await dbAccess.SaveAsync(item);
});
await Task.WhenAll(tasks);
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