鉴于此实体框架核心代码段
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> });这在 SaveChangesAsync 中因并发问题 (DataContext) 失败.然后我尝试了
This fails in SaveChangesAsync for concurrency issues (DataContext). Then I tried
await Task.WhenAll( list.Select( async entity => { <snippet> } ) );这成功了.我知道他们做的事情不同(ForEach 对输入列表进行分区,...),但是我想了解 Foreach 版本失败时的情况.
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.
推荐答案我想了解 Foreach 版本何时失败.
I would like to understand while the Foreach version fails.
ForEach 不理解 async lambdas.由于 ForEach 参数属于 Action 类型,async lambda 被转换为 async void 方法.async void 方法 的问题是调用代码不容易确定它何时完成,所以 ForEach 循环似乎提前"结束- 在 async void lambdas 完成之前.
ForEach doesn't understand async lambdas. Since the ForEach parameter is of type Action, the async lambda is converted to an async void method. One of the problems with async void methods is that it's not easy for the calling code to determine when it has completed, so the ForEach loop appears to end "early" - before the async void lambdas have completed.
async void 已添加到语言中以启用 async 事件处理程序,但这不是事件处理程序,因此使用 async void 这里是 lambdas.
async void was added to the language to enable async event handlers, but this is not an event handler, so it's not correct to use async void lambdas here.
更多推荐
将 Task.WhenAll 和 Parallel.ForEach 与 Entity Framework Core DataContext 一起使用时出现意外的
发布评论