【问题标题】:How could run sql query during using await async在使用等待异步期间如何运行 sql 查询
【发布时间】:2018-02-28 00:56:03
【问题描述】:

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

我可以在我的 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-async 时可以正常工作

【问题讨论】:

  • 您发布的代码与您遇到的异常无关。答案已经是 SO 上的 herehere 以及 codeproject 上的 here
  • @m.rogalski 问题是关于在使用 entity 期间使用 await-async 的方式,实体代码在没有 await-async 时可以正常工作
  • UpdateActivity 内部发生了什么,尤其是。那里使用了哪个上下文实例?

标签: c# entity-framework async-await


【解决方案1】:

让我们试试这个

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

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


return information;
}

返回任务,而不是字符串

【讨论】:

    【解决方案2】:

    不妨试试

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

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

    另外,如果在 GetName 函数之外创建 DbContext,它可以在 UpdateActivity 和 SendNotification 执行之前被释放,因为你不能等待 GetName。为此,您需要按照 Dan 的建议返回 Task

    【讨论】:

      【解决方案3】:

      我认为那是因为 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
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-06
        • 2020-06-19
        相关资源
        最近更新 更多