Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在使用await async期间运行sql查询_C#_Entity Framework_Async Await - Fatal编程技术网

C# 如何在使用await async期间运行sql查询

C# 如何在使用await async期间运行sql查询,c#,entity-framework,async-await,C#,Entity Framework,Async Await,在我的小项目中,我尝试保存一些数据或向用户发送通知 我可以在我的c代码上使用wait/async,甚至在将数据发送到客户端之后也可以运行查询吗 以下是示例: async string GetName(long userId) { string information=""; // loading data with entity await Task.Run(() => UpdateActivity(userId)); await Task.Run(() => SendNotif

在我的小项目中,我尝试保存一些数据或向用户发送通知

我可以在我的c代码上使用wait/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中发生,但未在用户代码中处理

其他信息:基础提供程序在打开时失败

实体代码,在我没有使用wait async时可以正常工作

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

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


return information;
}
异步任务GetName(长用户ID) { string information=“;//使用实体加载数据 等待任务。运行(()=>UpdateActivity(userId)); 等待任务。运行(()=>SendNotification(userId)); 返回信息; } 返回任务,而不是字符串

可以尝试

await Task.Run(() => UpdateActivity(userId)).ConfigureAwait(false);
await Task.Run(() => SendNotification(userId)).ConfigureAwait(false);
这将使GetName函数保持在相同的上下文中


此外,如果在GetName函数之外创建DbContext,则可以在执行UpdateActivity和SendNotification之前释放它,因为您不能等待GetName。为此,您需要返回Task,正如Dan所建议的,我认为这是因为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
}
异步任务GetName(长用户ID) { string information=“;//使用实体加载数据 DbContext=\u context//您的DbContext wait Task.Run(()=>UpdateActivity(userId,context)); 返回信息; } void UpdateActivity(int userId,DbContext上下文) { //使用上下文执行DBO操作 }
您发布的代码与您收到的异常情况无关。在codeproject上已经有了答案。@m.rogalski的问题是关于在使用实体时使用await async的方法,实体代码在没有await async时工作正常,
UpdateActivity
内部发生了什么,特别是在那里使用了哪个上下文实例?