Given this Entity Framework Core snippet
using (var scope = serviceProvider.CreateScope()) {
var ctx = scope.ServiceProvider.GetRequiredService<IEFCoreDataContext>();
// async operations on ctx and entity (see below for entity)
await ctx.SaveChangesAsync();
}
And a List<> of entities I want to use it in a concurrent way. I first tried
await Task.Run(() => Parallel.ForEach(list, async entity => {
<snippet>
});
This fails in SaveChangesAsync for concurrency issues (DataContext). Then I tried
await Task.WhenAll(
list.Select(
async entity => {
<snippet>
}
)
);
And this succeeds. I know they do things differently (ForEach partitions the input list, ...), however I would like to understand while the Foreach version fails.