如何使实体框架异步执行 [英] How to make Entity Framework execute asynchronously
问题描述
我正在使用Entity Framework 6 Code First方法。
我有一个方法
public async任务< ActionResult> index()
{
using(var context = new MyDbContext())
{
var eventsTask = context.Events
.Where(e => e。启用)
.ToListAsync();
var countTask = context.Users
.CountAsync();
等待Task.WhenAll(eventsTask,countTask);
return View(new ViewModel()
{
Events = eventsTask.Result,
Count = countTask.Result
});
}
}
这里有两个异步方法。我已经通过MiniProfiler分别测量了它们。他们需要〜85 ms。
但是在我的方法中,我使用Task.WhenAll()运行它们。我相信它以异步方式执行Db查询,两者都需要约85-90 ms。但需要〜170-180。所以我有异步方法同步运行(相互之间)。
我认为这是因为上下文。我有一个测试,当我删除上下文查询和使用HttpClient调用许多api方法。它需要时间等于更长的时间(3个api调用,每个约500毫秒),总共方法需要〜600 ms)。我相信可以异步执行EF方法。
有谁知道解决方案
这实际上不应该起作用,而是抛出异常。我猜第一个查询在第二个查询完成之前甚至开始。
等待
每个查询(因此它们不会同时运行),或者为每个查询使用不同的上下文。
I have problem with asynchronous controller in ASP.Net MVC 5 application. I'm using Entity Framework 6 Code First approach.
I have a method
public async Task<ActionResult> Index()
{
using(var context = new MyDbContext())
{
var eventsTask = context.Events
.Where(e => e.Enable)
.ToListAsync();
var countTask = context.Users
.CountAsync();
await Task.WhenAll(eventsTask, countTask);
return View(new ViewModel()
{
Events = eventsTask.Result,
Count = countTask.Result
});
}
}
I have two asyncronous methods here. I have measured each of them separately via MiniProfiler. They takes ~85 ms.
But in my method I run them using Task.WhenAll(). I believe it executes Db queries asynchronously and should take about ~85-90 ms for both. But it takes ~170-180. So I have got asynchronous methods run synchronously (following each other).
I think it is because of context. I have a test, when I remove context queries and call many api methods using HttpClient. It takes time equals to longer of them (3 api calling, ~500 ms each of them. Totally method takes ~600 ms). I believe that It is possible to execute EF methods asynchronously.
Does anyone know the solution
This shouldn't even work actually, but throw an exception instead. I'm guessing the first query completes before the second one even starts.
EF6 doesn't support multiple async operations on the same context.
Either await
each query (so they won't run concurrently), or use a different context for each query.
这篇关于如何使实体框架异步执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!