SqlConnection的SqlCommand的SqlDataReader的IDisposable的 [英] SqlConnection SqlCommand SqlDataReader IDisposable

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

问题描述

的SqlConnection 的SqlCommand SqlDataReader的都实现了IDisposable的接口<$ C C $>。我读到一个最佳实践,始终包裹 IDisposables 使用块。

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;
        }
    }
}

这是正确的做法,或者可以说被认为是矫枉过正?我对嵌套使用块这个水平有点不确定,但我当然想这样做的正确方法。 谢谢!

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 应该被包在使用语句,以确保处置()方法被调用。此外,随着-unmanaged在那样的SQL Server外部技术交流不应该掉以轻心。该的SqlCommand 对象实现的IDisposable 一个很好的理由。在code以下是的Dispose()方法为的SqlCommand 目标:

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天全站免登陆