EF 6-如何正确执行并行查询 [英] EF 6 - How to correctly perform parallel queries
问题描述
创建报告时,我必须执行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);
}
推荐答案
问题是这样的:
EF不支持通过同一个DbContext对象处理多个请求。如果您在同一个DbContext实例上的第二个异步请求在第一个请求完成之前开始(这很重要),则会收到一条错误消息,表明您的请求正在针对打开的DataReader处理。
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
您将需要将您的代码修改为以下内容:
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-如何正确执行并行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!