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