Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a bunch async tasks when a certain execution order needs to be preserved

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 ?

like image 482
AstroSharp Avatar asked Feb 25 '16 16:02

AstroSharp


People also ask

Can async method have multiple awaits?

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).

Does Task WhenAll run in parallel?

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.

What is Task run async?

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.


1 Answers

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);
like image 186
Servy Avatar answered Oct 27 '22 00:10

Servy