问题描述
创建报告时,我必须执行 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 不支持通过同一个 DbContext 对象处理多个请求.如果您对同一个 DbContext 实例的第二个异步请求在第一个请求完成之前开始(这就是重点),您将收到一条错误消息,表明您的请求正在针对打开的 DataReader 进行处理.
来源:https://visualstudiomagazine.com/articles/2014/04/01/async-processing.aspx
您需要将代码修改为如下所示:
async Task>获取E1Data(){使用(var MyCtx = new MyCtx()){返回等待 MyCtx.E1.Where(bla bla bla).ToListAsync();}}异步任务>获取E2Data(){使用(var MyCtx = new MyCtx()){返回等待 MyCtx.E2.Where(bla bla bla).ToListAsync();}}异步任务 DoSomething(){var t1 = GetE1Data();var t2 = GetE2Data();等待 Task.WhenAll(t1,t2);DoSomething(t1.Result, t2.Result);}
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...
What is the correct way to perform queries in parallel using EF 6? Should I manually start new Tasks?
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);
}
The problem is this:
Source: 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 - 如何正确执行并行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!