I've been reading up on executing tasks in parallel. I have multiple database row updates (each one independent) that need to occur. Instead of updating one row at a time, I want to update them all at once. Note in below code that dbConnection.ExecuteAsync
returns a Task<int>
(i.e. # of rows updated/deleted).
Below is my current approach:
var deleteTasks = new List<Task<int>>();
foreach (var item in queries)
{
deleteTasks.Add(dbConnection.ExecuteAsync(item.RawSql, item.Parameters, transaction: transaction));
}
//ensure all queries are complete
await Task.WhenAll(deleteTasks);
Now above approach works, but I've also seen below two approaches:
var deleteTasksSelect1 = queries.Select(query => (dbConnection.ExecuteAsync(query.RawSql, query.Parameters, transaction: transaction)));
var deleteTasksSelect2 = queries.Select(async query => await (dbConnection.ExecuteAsync(query.RawSql, query.Parameters, transaction: transaction)));
Both of them return IEnumerable<Task<int>>
. I'm trying to understand what the difference is between my approach above and the LINQ projections. One of them builds up an async Func while the other does not but both return the same result. What is the difference between these and what is the correct approach?
Note that for getting my results (i.e. the # of rows affected, I do below after my call to Task.WhenAll()):
var successCount = deleteTasks.Sum(x => x.Result)