Aym*_*udi 1 c# linq asynchronous entity-framework async-await
我正在尝试使用.ToListAsync()Inside a DbContext的using语句获取linq查询结果,代码:
private async Task<List<String>> GetEntiteesAsync()
{
Task<List<String>> returnValue;
using (var entities = new REPORTEntities())
{
returnValue = (from user in entities.USERs
group user by user.entite into g
select g.Key).ToListAsync();
}
return await returnValue;
}
Run Code Online (Sandbox Code Playgroud)
在运行时,我得到"已经处理了ObjectContext实例,不能再用于需要连接的操作." 如图所示 :

我认为这是由于在returnValue对象仍然像List一样异步接收对象的情况下处理Context这一事实引起的,是否有一种解决方法可以在保留using语句时避免此错误,或者我应该这样做:
private async Task<List<String>> GetEntiteesAsync()
{
Task<List<String>> returnValue;
var entities = new REPORTEntities()
returnValue = (from user in entities.USERs
group user by user.entite into g
select g.Key).ToListAsync();
return await returnValue;
}
Run Code Online (Sandbox Code Playgroud)
您将using在ToListAsync操作完成之前离开作用域,因为您没有等待异步任务,这意味着entities处理太快(因此对象处置异常).
您应该只在范围内返回结果,并且async-await机制将确保Dispose在操作异步完成后调用:
private async Task<List<String>> GetEntiteesAsync()
{
using (var entities = new REPORTEntities())
{
return await (from user in entities.USERs
group user by user.entite into g
select g.Key).ToListAsync();
}
}
Run Code Online (Sandbox Code Playgroud)