Asynchronously saving to multiple tables in a single SQL Server Db

async-await asynchronous c# entity-framework-core

Question

I was able to populate multiple tables of a database in parallel using Task.WhenAll(tasks). I have a generic method for each table:

var tasks = new List<Task>()
        {
            CheckNewItems<S, T>(async () => await GetPrimaryKeys<S, T>(),
            CheckNewItems<S, T>(async () => await GetPrimaryKeys<S, T>(),
            CheckNewItems<S, T>(async () => await GetPrimaryKeys<S,T>(),                                                                     
            CheckNewItems<S, T>(async () => await GetPrimaryKeys<S,T>()
        };

        await Task.WhenAll(tasks);

Now a new requirement came that asks me to save the number of new items from that async method, and I stumbled into this post. I tried to do it the way its mentioned in the comments on the accepted answer, to get the number of new items:

   int newItems = 0;
   newItems += await CheckNewItems<S, T>(async () => await GetPrimaryKeys<S, T>();
   newItems += await CheckNewItems<S, T>(async () => await GetPrimaryKeys<S, T>();
   newItems += await CheckNewItems<S, T>(async () => await GetPrimaryKeys<S,T>();                                                                     
   newItems += await CheckNewItems<S, T>(async () => await GetPrimaryKeys<S,T>();

Using the second method, the database tables do not update in parallel but synchronously.

Inside that CheckNewItem method, I'm using the SaveChangesAsync and AddRangeAsync methods in EF Core. I'm not sure why using Task.WhenAll(tasks) does the desired action and doing it the second way doesn't when in the post some of the comments mentioned that you don't need to do Task.WhenAll to make sure async methods run in parallel.

I would like to get the results of each call to CheckNewItems, while they can still save to the database asynchronously and in parallel as usual. Thanks in advance for the insights and help :)

1
0
1/29/2020 12:46:13 AM

Popular Answer

How about:

var tasks = new List<Task>()
        {
            CheckNewItems<S, T>(async () => await GetPrimaryKeys<S, T>(),
            CheckNewItems<S, T>(async () => await GetPrimaryKeys<S, T>(),
            CheckNewItems<S, T>(async () => await GetPrimaryKeys<S,T>(),                                                                     
            CheckNewItems<S, T>(async () => await GetPrimaryKeys<S,T>()
        };

await Task.WhenAll(tasks);
int newItems = 0;
foreach(var task in tasks){
     newItems+= await task;
}
1
1/29/2020 1:12:43 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow