【问题标题】:DbConnection.StateChange not called when connection is disposed?处理连接时未调用 DbConnection.StateChange?
【发布时间】:2012-11-22 15:50:00
【问题描述】:

我有一个可以同时从数百个线程访问的单例数据库类。每个线程都有自己的连接。由于无法控制线程数,所以需要限制并发连接数。我决定使用如下所示的信号量。现在,连接总是在 using 块中分配,因此它确实可以保证关闭 - 即使抛出异常。

但是,当抛出异常时,StateChange 似乎没有被调用。显然,这破坏了我下面的代码。

问题:如何确保在这种情况下确实调用了StateChange?或者,如果不可能,我该如何解决这个特殊问题?

private const int MAX_CONNECTIONS = 10;
private static SemaphoreSlim connectionLock = new SemaphoreSlim(MAX_CONNECTIONS);

protected DbConnection OpenConnection()
{
    var connection = ProviderFactory.CreateConnection();
    connection.ConnectionString = ConnectionString;
    connection.Open();

    connectionLock.Wait();

    connection.StateChange += (s, e) =>
    {
        if (e.CurrentState == ConnectionState.Closed)
        {
            connectionLock.Release();
        }
    };

    return connection;
}

【问题讨论】:

  • 请问为什么不能使用默认的ADO.NET Connection-Pooling
  • 不确定这有什么帮助?如果达到最大连接数,线程应该如上所示等待。

标签: c# semaphore idisposable dbconnection


【解决方案1】:

好的...如果异常是在调用OpenConnection 之后产生的,似乎确实调用了该事件。当我对此进行测试时,我在返回连接之前添加了一个明确的throw new Exception()...哎呀!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    相关资源
    最近更新 更多