为什么不是配置的SqlConnection /关闭? [英] Why isn't SqlConnection disposed/closed?

查看:118
本文介绍了为什么不是配置的SqlConnection /关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出的方法:

internal static DataSet SelectDataSet(String commandText, DataBaseEnum dataBase)
{
    var dataset = new DataSet();

    SqlConnection sqlc = dataBase == DataBaseEnum.ZipCodeDb
                             ? new SqlConnection(ConfigurationManager.AppSettings["ZipcodeDB"])
                             : new SqlConnection(ConfigurationManager.AppSettings["WeatherDB"]);
    SqlCommand sqlcmd = sqlc.CreateCommand();
    sqlcmd.CommandText = commandText;
    var adapter = new SqlDataAdapter(sqlcmd.CommandText, sqlc);
    adapter.Fill(dataset);


    return dataset;
}

为什么SQLC(关闭SqlConnection)没有设置/关闭调用方法超出范围后或者SQLC没有更多的参考?

Why is sqlc (the SqlConnection) not disposed/close after the calling method goes out of scope or sqlc has no more references?

编辑1:
即使是包装用,我还可以看到使用的连接(我已经连接池关闭):

EDIT 1: Even wrapping it in using, I can still seeing the connection using (I have connection pooling turned off):

SELECT DB_NAME(dbid) as 'Database Name',
COUNT(dbid) as 'Total Connections'
FROM sys.sysprocesses WITH (nolock)
WHERE dbid > 0
GROUP BY dbid

编辑2:
有帮助一些调试我从这里得到 - 答案是有人硬codeD的连接字符串池。感谢所有帮助 - 如果我可以,我会标记所有的答复为答案

EDIT 2: Have some more debugging with help I got from here - the answer was the someone hard coded a connection string with pooling. Thanks for all the help - if I could, I would mark all the responses as answers.

推荐答案

C#的垃圾回收具有不确定性,但语言确实提供了资源配置这样一个确定性的结构:

C#'s garbage collection is non-deterministic but the language does provide a deterministic structure for resource disposal like this:

using (SqlConnection connection = new SqlConnection(...))
{
    // ...  
}

这将创建一个尝试/终于块,这将确保连接对象无论在方法会发生什么处理。你真的应该换行的实现类型的IDisposable 的任何实例using块这样的,因为这将确保负责任的资源管理(如数据库连接非托管资源的),并且也给出了你,你正在寻找的确定性控制。

This will create a try/finally block which will ensure that the connection object is disposed regardless of what happens in the method. You really ought to wrap any instances of types that implement IDisposable in a using block like this as it will ensure responsibly resource management (of unmanaged resources like database connections) and also it gives you the deterministic control you are looking for.

这篇关于为什么不是配置的SqlConnection /关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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