c# – EF 6 – 如何正确执行并行查询

在创建报告时,我必须执行3个涉及相同上下文的分离实体的查询.因为它们很重,我决定使用.ToListAsync();为了让它们并行运行,但令我惊讶的是,我得到了一个例外…

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

编辑1
代码基本上是

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);
}
问题是这样的:

EF doesn’t support processing multiple requests through the same DbContext object. If your second asynchronous request on the same DbContext instance starts before the first request finishes (and that’s the whole point), you’ll get an error message that your request is processing against an open DataReader.

资料来源:https://visualstudiomagazine.com/articles/2014/04/01/async-processing.aspx

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

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(r1.Result, r2.Result);
}
https://stackoverflow.com/questions/41749896/ef-6-how-to-correctly-perform-parallel-queries

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c# – EF 6 – 如何正确执行并行查询