SqlConnection SqlCommand SqlDataReader IDisposable [英] SqlConnection SqlCommand SqlDataReader IDisposable

查看:17
本文介绍了SqlConnection SqlCommand SqlDataReader IDisposable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SqlConnectionSqlCommandSqlDataReader 都实现了IDisposable 接口.我读到了始终将 IDisposables 包装到 using 块中的最佳实践.

SqlConnection, SqlCommand and SqlDataReader all implement the IDisposable interface. I read about a best practice to always wrap IDisposables into a using block.

所以,我查询数据的常见场景看起来像这样(在更大的上下文中,像 linq2sql 这样的映射工具当然是合适的,但假设我们想在这里使用这种方法):

So, my common scenario for querying data would look something like this (in greater context of course a mapping tool like linq2sql would be suitable, but lets just assume we want to use this approach here):

using (SqlConnection cn = new SqlConnection("myConnectionstring"))
{
    using (SqlCommand cm = new SqlCommand("myQuery", cn))
    {
        // maybe add sql parameters
        using (SqlDataReader reader = cm.ExecuteReader())
        {
             // read values from reader object
             return myReadValues;
        }
    }
}

这是正确的方法还是被认为是矫枉过正?我对这种嵌套 using 块的级别有点不确定,但我当然想以正确的方式来做.谢谢!

Is this the correct way or could that be considered overkill? I am a little unsure about this level of nesting using blocks, but of course i want to do it the correct way. Thanks!

推荐答案

这是 100% 正确的方法.如果一个类利用了 IDisposable 它应该被包装在一个 using 语句中以确保调用 Dispose() 方法.此外,不应掉以轻心,与诸如 SQL Server 之类的不受管理的外部技术进行通信.SqlCommand 对象实现 IDisposable 是有充分理由的.下面的代码是 SqlCommand 对象的 Dispose() 方法:

This is 100% the correct way. If a class leverages IDisposable it should be wrapped in a using statement to ensure that the Dispose() method is called. Further, communicating with an outside technology -unmanaged at that -like SQL Server shouldn't be taken lightly. The SqlCommand object implements IDisposable for a very good reason. The code below is the Dispose() method for the SqlCommand object:

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this._cachedMetaData = null;
    }
    base.Dispose(disposing);
}

如您所见,它正在释放对 _cachedMetaData 对象的引用,以便清理它.

and as you can see, it's releasing a reference to the _cachedMetaData object so that it too can get cleaned up.

这篇关于SqlConnection SqlCommand SqlDataReader IDisposable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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