妥善弃置一的DbConnection的 [英] Properly disposing of a DbConnection

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

问题描述

我有一个叫DatabaseHelper类,包装了一个的DbConnection。什么是设置的正确方法这个类using语句?我已经实现IDisposible,但我不知道何时何地我应该调用connection.close()时或Connection.Dispose()。

I have a class called DatabaseHelper that wraps a DbConnection. What's the proper way to setup this class for a using statement? I have implemented IDisposible, but I'm not sure when and where I should be calling Connection.Close() or Connection.Dispose().

当我只需拨打连接.Dispose()在我自己的Dispose()方法,我有时会从我的DbConnection对象SocketException异常。我想这是因为旧的连接正在开着,但没有附到异常的详细信息,所以无法知道。

When I simply call Connection.Dispose() in my own Dispose() method, I'll sometimes get a SocketException from my DbConnection object. I assume this is because old connections are being left open, but there's no details attached the to exception, so I can't know for sure.

推荐答案

从您的Dispose方法中调用connection.Dispose()。你应该看看在标准模式实现IDisposable的,它超越简单的实现IDisposable接口的状态,并允许处理非托管对象等:

Call connection.Dispose() from within your dispose method. You should look at the standard pattern for implementing IDisposable, which goes above and beyond simply implementing the IDisposable interface and allows for disposing unmanaged objects etc:

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
    if (!disposed)
    {
        if (disposing)
        {
            // Dispose managed resources.
        }

        // There are no unmanaged resources to release, but
        // if we add them, they need to be released here.
    }
    disposed = true;

    // If it is available, make the call to the
    // base class's Dispose(Boolean) method
    base.Dispose(disposing);
}



(从的 http://msdn.microsoft.com/en-us/library/system.idisposable.aspx )。

这篇关于妥善弃置一的DbConnection的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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