Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach with async c#

Tags:

c#

.net-core

Im calling async method like this:

foreach (var item in someList)
{
    item.someValue = asdf.Where(() => SomeMethod(item)).FirstOrDefaultAsync();
}

How do I get it to work asynchronously? I want to await all results. I'm using .Net Core 3.1

like image 363
Maciejowski Avatar asked Nov 24 '25 03:11

Maciejowski


2 Answers

For asynchronous concurrency, the best approach is to use await Task.WhenAll:

var tasks = someList.Select(async item =>
{
  item.someValue = await asdf.Where(() => SomeMethod(item)).FirstOrDefaultAsync();
});
await Task.WhenAll(tasks);

However, it looks like you might be using Entity Framework. In that case, you'll need to be aware that Entity Framework does not support multiple concurrent queries on the same context. You will either need to run your queries one at a time, or use multiple db contexts.

like image 97
Stephen Cleary Avatar answered Nov 25 '25 17:11

Stephen Cleary


You can try something like below

var myTasks = someList.Select(async x => 
{
   //Your code here
});

Await for all the tasks to complete

await Task.WhenAll(myTasks);
like image 26
Rahul Avatar answered Nov 25 '25 16:11

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!