如何同时对我的webapi进行多个异步调用而不会出现错误?

时间:2019-06-03 14:29:15

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

当我执行1次访存时我遇到问题,但是当我尝试同时1次成功访存4个电话而其他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.

当我在Google上搜索时,他们建议我添加到连接字符串

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)));在第一行代码中,我做了很多选择和类似的事情。如果我在这里删除一些繁重的代码,它就可以工作。但这似乎是问题所在,这些东西无法处理多个呼叫。我的意思是,这应取决于完成后应返回的作业的大小。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

从我的头顶尝试

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

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

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