将 Task.WhenAll 和 Parallel.ForEach 与 Entity Framework Core DataContext 一起使用时出现意外的不同结果

编程入门 行业动态 更新时间:2024-10-28 18:31:29
本文介绍了将 Task.WhenAll 和 Parallel.ForEach 与 Entity Framework Core DataContext 一起使用时出现意外的不同结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

鉴于此实体框架核心代码段

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 一起使用时出现意外的

本文发布于:2023-11-14 16:24:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587946.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:意外   Parallel   ForEach   Task   WhenAll

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!