简体   繁体   English

EF Core 2.1 - 处理并行异步方法的连接

[英]EF Core 2.1 - Handling connection on parallel async methods

I have multiple async methods in my DbContext to call stored procedures.我的 DbContext 中有多个异步方法来调用存储过程。 All those methods handle connections as below.所有这些方法处理连接如下。

        DbConnection connection = this.Database.GetDbConnection();
        bool needClose = false;
        if (connection.State != ConnectionState.Open)
        {
            connection.OpenAsync();
            needClose = true;
        }
        }
        try {}
        finally
        {
            if (needClose)
                connection.Close();
        }

I'm calling some of these methods in parallel.我正在并行调用其中一些方法。 My connection string has MultipleActiveResultSets=True.我的连接字符串有 MultipleActiveResultSets=True。 I'm getting below error because the connection get closed by another method.我收到以下错误,因为连接被另一种方法关闭。

Invalid operation.无效操作。 The connection is closed连接已关闭

What would be a better approach for this?什么是更好的方法呢? Thanks in advance.提前致谢。

Currently I'm closing the connection on dispose.目前我正在关闭处理连接。 It looks good.这看起来不错的样子。 But if you have any other suggestions please let me know.但是,如果您有任何其他建议,请告诉我。

    public override void Dispose()
    {
        DbConnection connection = Database.GetDbConnection();
        if (connection.State != ConnectionState.Closed)
        {
            connection.Close();
        }
        base.Dispose();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM