I switched to .net Core for some projects and now I have a problem with Parallel.ForEach. Previously, I often had a list of id values that I would then use to create web requests to get complete data. It will look something like this:
Parallel.ForEach(myList, l =>
{
});
Well, in .net Core, web requests should be tagged await, which means that the Parallel.ForEach action needs to be tagged async. But, marking the action of Parallel.ForEach as async, we have a method void asyncthat causes problems. In my specific case, this means that the response is returned to the application before all web requests in the Parallel loop are completed, which is inconvenient and causes errors.
Question: What are the alternatives to using Parallel.ForEach here?
One of the possible solutions that I found is to wrap the Parallel loop inside the task and wait for the task:
await Task.Run(() => Parallel.ForEach(myList, l =>
{
// stuff here
}));
(found here: Parallel .ForEach and Task.Run and Task.WhenAll )
But this does not work for me. When I use this, I still get back to the application until the loop ends.
Another option:
var tasks = new List<Task>();
foreach (var l in myList)
{
tasks.Add(Task.Run(async () =>
{
}));
}
await Task.WhenAll(tasks);
It works, but is it the only option? It seems that the new .net Core has made Parallel.ForEach practically useless (at least when it comes to nested web calls).
Any help / advice is appreciated.
source
share