我可以依靠using语句关闭我的MySQL连接吗? [英] Can I rely on the using statement to close my MySQL connections?

查看:106
本文介绍了我可以依靠using语句关闭我的MySQL连接吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用mysql作为数据库的ASP.NET网站.当显示完整的进程列表时,我注意到有很多连接处于睡眠状态".今天,我们遇到了一些错误:从池中获取连接之前,超时时间已经过去."如果进程处于休眠"状态,那么它们是否仍从代码中打开?代码中的所有MySQL连接都在using语句中.我可以依靠using语句正确关闭连接吗?

I have an ASP.NET website that uses mysql as it's database. I notice there are a lot of connections "sleeping" when I show a full process list. Today we had some errors "The timeout period elapsed prior to obtaining a connection from the pool.". If the processes are "sleeping" then are they still open from the code? All MySQL connections in the code are in using statements. Can I rely on the using statement to properly close connections?

编辑代码: 我正在使用此类来创建我的连接:

Edit Code: I am using this class to create my connection:

public class DbAccess
{
    public static MySqlConnection OpenConnection(string connectionStringName)
    {
        string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
        if (string.IsNullOrEmpty(connectionString))
        {
            throw new ArgumentException("Connection string " + connectionStringName + " does not exist.");
        }
        MySqlConnection connection = new MySqlConnection(connectionString);
        connection.Open();
        return connection;
    }
}

然后我这样称呼它:

using (MySqlConnection connection = DbAccess.OpenConnection(connectionString))
{
    //Code Here
}

一些其他信息:重置MySql不会使错误消失,但是重置我的应用程序池却可以.

Some additional info: Resetting MySql did not make the errors go away, but resetting my app pool did..

推荐答案

使用C#的块可以保证调用对象的.Dispose()方法,即使抛出异常也是如此.这意味着只有您的提供者将使用.Dispose()方法关闭连接时,它才是安全的.查看该类型的文档 ,我看到了此摘录(见第25.2.3.3.5节):

C# using blocks are guaranteed to call the .Dispose() method of the object, even if an exception is thrown. That means it's safe, only if your provider will use the .Dispose() method to close the connection. Looking in the documentation for that type, I see this excerpt (down in section 25.2.3.3.5):

使用连接对象的Close方法或Dispose方法从打开"到关闭".

From Open to Closed, using either the Close method or the Dispose method of the connection object.

这告诉我可以通过Dispose方法关闭连接,因此using块应该就足够了.

This tells me you can close the connection via the Dispose method, and so a using block should be all you need.

这篇关于我可以依靠using语句关闭我的MySQL连接吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆