2017-09-19 46 views
2

在我的小项目上,我尝试保存一些数据或向用户发送通知。如何在使用等待异步期间运行sql查询

即使在向客户端发送数据之后,我是否可以对我的c#代码使用await/async并进行查询运行?

下面是示例:

async string GetName(long userId) 
{ 
string information=""; // loading data with entity 

await Task.Run(() => UpdateActivity(userId)); 
await Task.Run(() => SendNotification(userId)); 


return information; 
} 

void UpdateActivity(long userId) 
{ 
// loading data with entity 
// updating activity 
} 

void SendNotification(long userId) 
{ 
// loading data with entity 
// Sending Notification 
} 

这是在与实体

发生类型“System.Data.Entity.Core.EntityException” 的例外加载数据我的问题之一在mscorlib.dll中但未在用户代码中处理

附加信息:底层提供程序在打开时失败。

实体的代码,当我还没有使用的await,异步

+5

您发布的代码与您遇到的异常无关。一个答案已经[这里](https://stackoverflow.com/questions/18271301/entity-framework-the-underlying-provider-failed-on-open)和[这里](https://stackoverflow.com/questions/2475008/mssql-error-the-underlying-provider-failed-on-open)on SO and [here](https://www.codeproject.com/Tips/126919/Solution-for-The-underlying-provider-代码项目上的失败。 –

+4

@ m.rogalski问题是关于在使用实体期间使用await-async的方式,实体代码在没有等待时异常工作 - async – Meysam

+0

'UpdateActivity'内发生了什么,哪个上下文实例在那里使用? –

回答

2

让我们试试这个

async Task<string> GetName(long userId) 
{ 
string information=""; // loading data with entity 

await Task.Run(() => UpdateActivity(userId)); 
await Task.Run(() => SendNotification(userId)); 


return information; 
} 

返回工作,不串

0

也许尝试

工作正常
await Task.Run(() => UpdateActivity(userId)).ConfigureAwait(false); 
await Task.Run(() => SendNotification(userId)).ConfigureAwait(false); 

这将使GetName函数保持在相同的上下文中。

另外,如果在GetName函数外部创建DbContext,则可以在执行UpdateActivity和SendNotification之前处理它,因为您无法等待GetName。因为你需要返回任务,因为丹你建议

0

我认为这是因为dbContext不可用于并行任务,因为你已经只将userId传递给最终引用dbcontext执行dbOperation的并行任务。你需要为此改变架构。

async Task<string> GetName(long userId) 
{ 
string information=""; // loading data with entity 
DbContext context = _context// Your dbContext 
await Task.Run(() => UpdateActivity(userId, context)); 


return information; 
} 

void UpdateActivity(int userId, DbContext context) 
{ 
    //perform dboperation with context 
}