如何正确执行并行查询

如何正确执行并行查询

本文介绍了EF 6-如何正确执行并行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建报告时,我必须执行3个查询,这些查询涉及相同上下文的分离实体。因为它们很重,所以我决定使用 .ToListAsync(); 使其并行运行,但是令我惊讶的是,它...

When creating a report I have to execute 3 queries that involve separated entities of the same context. Because they are quite heavy ones I decided to use the .ToListAsync(); in order to have them run in parallel, but, to my surprise, I get a exception out of it...

使用EF 6并行执行查询的正确方法是什么?我应该手动启动新任务吗?

What is the correct way to perform queries in parallel using EF 6? Should I manually start new Tasks?

编辑1

代码基本上是

Edit 1
The code is basically

using(var MyCtx = new MyCtx())
{
      var r1 = MyCtx.E1.Where(bla bla bla).ToListAsync();
      var r2 = MyCtx.E2.Where(ble ble ble).ToListAsync();
      var r3 = MyCtx.E3.Where(ble ble ble).ToListAsync();
      Task.WhenAll(r1,r2,r3);
      DoSomething(r1.Result, r2.Result, r3.Result);
}


推荐答案

问题是这样的:

来源:

您将需要将您的代码修改为以下内容:

You will need to modify your code to something like this:

async Task<List<E1Entity>> GetE1Data()
{
    using(var MyCtx = new MyCtx())
    {
         return await MyCtx.E1.Where(bla bla bla).ToListAsync();
    }
}

async Task<List<E2Entity>> GetE2Data()
{
    using(var MyCtx = new MyCtx())
    {
         return await MyCtx.E2.Where(bla bla bla).ToListAsync();
    }
}

async Task DoSomething()
{
    var t1 = GetE1Data();
    var t2 = GetE2Data();
    await Task.WhenAll(t1,t2);
    DoSomething(t1.Result, t2.Result);
}

这篇关于EF 6-如何正确执行并行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 22:43