将 Task.WhenAll 和 Parallel.ForEach 与 Entity Framework Core DataContext 一起使用时出现意外的不同结果 [英] Unexpected different results using Task.WhenAll and Parallel.ForEach with an Entity Framework Core DataContext

查看:11
本文介绍了将 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<是不正确的/code> 这里是 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 一起使用时出现意外的不同结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆