2

I'm using the latest stable MySql Connector/NET 6.5.4.0.

I open a connection to a MySQL database. In the C# code, the Connection.State property is Open. I do some magic stuf, and while I'm doing that, I kill the connection server side. However, in the code the State is still Open.

I ran into this problem because I save instances of my database class in a static variable per session (Dictionary). If a user does a request, the database class is pulled from this variable, and queries are fired to it. However, if the connection closes server side (killed by de sysadmin, wait timeout elapsed), the state isn't updated.

Is there a workaround for this problem? My colleague allready submitted a bug report for it (http://bugs.mysql.com/bug.php?id=64991).

Close and Open before execution, is very bad for the performance, so no option.

4

2 回答 2

1

根据您的评论,抛开设计问题(应该是池化):

在这种情况下连接池被关闭,我将研究 Ping 方法。如果此连接关闭,我会收到“命令执行期间遇到致命错误”

如果 ping 失败,您是否有任何理由不重新创建连接?

private static MySqlConnection conn;
private static int maxRetries;

private static void connect()
{
    conn = <connect code>;
}

private static MySqlConection GetConnectionRetry(int count)
{
    if (conn != null && conn.State == Open)
    {
        try
        {
            conn.Ping();
            return conn;
        }
        catch (Exception e) // better be specific here
        {
            if (count <= maxRetries)
            {
                connect();
                return GetConnectionRetry(count + 1);
            }
            else throw e;
        }
    }
    else
    {
        connect();
        return GetConnectionRetry(count + 1);
    }
}

static MySqlConnection GetConnection()
{
    return GetConnectionRetry(1);
}
于 2012-04-18T12:06:01.190 回答
0

我建议您使用单点模式进行连接。因此,您可以确保始终只有一个连接打开,您只需管理这个连接。

于 2012-04-18T09:48:03.967 回答