【问题标题】:How can i do multiple async calls to my webapi at the same time without getting errors?如何同时对我的 webapi 进行多个异步调用而不会出错?
【发布时间】:2019-10-19 03:06:24
【问题描述】:

当我进行 1 次获取时遇到问题,但当我尝试同时获取 4 次调用时,1 次成功,另外 3 次失败。

    public IHttpActionResult GetAll() {
        var products = _context.Products
            .ToList();

        if (products == null)
            return NotFound();

        return Ok(products.Select(x => CreateDto(x)));
    }

这是错误

An error has occurred.","ExceptionMessage":"There is already 
an open DataReader associated with this Command which must be 
closed first.

当我用谷歌搜索时,他们建议我添加到连接字符串中

MultipleActiveResultSets=True

然后我得到另一个错误

ExecuteReader requires an open and available Connection. 
The connection's current state is open.

google 的建议是这样的。我使用dbcontext 错误ExecuteReader requires an open and available Connection. The connection's current state is Connecting

我的 dbcontext 看起来像。所以我没有做任何时髦的事情。

public class PContext : DbContext {

    public IDbSet<Products> Products{ get; set; }

}

当我返回 Ok(products.Select(x => CreateDto(x)));在第一行代码中,我做了很多选择和类似的事情。如果我在这里删除一些繁重的代码,它就可以工作。但感觉问题在于这些东西无法处理多个呼叫。我的意思是它应该取决于它完成后应该返回的作业的大小。

有什么想法吗?

【问题讨论】:

  • 可能您在多个请求中使用了一个 dbcontext。确保为每个请求创建一个。
  • 我有一个运行受保护的只读 PContext _context 的基本控制器; public ApiControllerBase(PContext context) { _context = context; }
  • 什么时候创建上下文,传递给基本控制器的上下文?
  • 我不确定从控制器我调用 public ProductsController(PdbContext context) : base(context) { } 这很混乱。它没有调用新的
  • 我尝试调用 new 到 base 结果是一样的。它不工作

标签: c# asynchronous asp.net-web-api


【解决方案1】:

从我的头顶试试这个

public IHttpActionResult GetAll() {
    var products = _context.Products;

    if (products == null)
        return NotFound();
    var convertToListFirst = products.Select(x => CreateDto(x)).ToList();
    return Ok(convertToListFirst);
}

我记得过去在错误的时间转换为列表。

【讨论】:

  • 感谢您的意见。我已经尝试过了。然后我得到同样的错误:ExceptionMessage=ExecuteReader 需要一个打开且可用的连接。连接的当前状态是打开的。当设置 MultipleActiveResultSets=True 时。并且没有第一个错误:ExceptionMessage=已经有一个打开的 DataReader 与此命令关联,必须先关闭。
猜你喜欢
  • 1970-01-01
  • 2014-03-31
  • 1970-01-01
  • 1970-01-01
  • 2017-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多