正确处理DbConnection

时间:2008-12-22 17:09:54

标签: c# dispose dbconnection

我有一个名为DatabaseHelper的类,它包装了一个DbConnection。为using语句设置此类的正确方法是什么?我已经实现了IDisposible,但我不确定我应该何时何地调用Connection.Close()或Connection.Dispose()。

当我在我自己的Dispose()方法中调用Connection.Dispose()时,我有时会从DbConnection对象中获取SocketException。我认为这是因为旧的连接处于打开状态,但是没有附加到异常的详细信息,所以我无法确定。

4 个答案:

答案 0 :(得分:6)

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

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)。

答案 1 :(得分:2)

根据this新闻组:

以下是IDbConnection.Dispose()的实现方式(如Reflector实用程序所示):

的SqlClient:

protected override void Dispose(bool disposing)
{
       if (disposing)
       {
             switch (this._objectState)
             {
                   case ConnectionState.Open:
                   {
                         this.Close();
                         break;
                   }
             }
             this._constr = null;
       }
       base.Dispose(disposing);
}

Odbc:
protected override void Dispose(bool disposing)
{
       if (disposing)
       {
             this._constr = null;
             this.Close();
             CNativeBuffer buffer1 = this._buffer;
             if (buffer1 != null)
             {
                   buffer1.Dispose();
                   this._buffer = null;
             }
       }
       base.Dispose(disposing);
}

OleDb:
protected override void Dispose(bool disposing)
{
       if (disposing)
       {
             if (this.objectState != 0)
             {
                   this.DisposeManaged();
                   if (base.DesignMode)
                   {
                         OleDbConnection.ReleaseObjectPool();
                   }
                   this.OnStateChange(ConnectionState.Open, ConnectionState.Closed);
             }
             if (this.propertyIDSet != null)
             {
                   this.propertyIDSet.Dispose();
                   this.propertyIDSet = null;
             }
             this._constr = null;
       }
       base.Dispose(disposing);
}

您的dispose方法只应尝试在连接打开时关闭连接。

答案 2 :(得分:1)

这个析构函数语法实际上是终结器。终结器调用Dispose(false) 方法

    #region IDisposable Members
    private bool _isDisposed;

    private void ThrowIfDisposed()
    {
        if (_isDisposed)
            throw new ObjectDisposedException(this.GetType().Name);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!_isDisposed)
        {
            if (disposing)
            {
                //part 1 : disposing managed objects
                _command.Dispose();
                _command.Connection.Dispose();
                if (_command.Transaction != null)
                    _command.Transaction.Dispose();
            }
            //part 2: disposing unmanged objects. Here there are no unmanged objects.
            _isDisposed = true;
        }
    }

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

    //~DbCommandExecutor() //No need of finalize here. Because there is no unmanged objects in my class. ie, no code in part 2.
    //{
    //    Dispose(false);
    //}
    #endregion

在您的代码具有第2部分代码之前,不需要终结器(或析构函数)语法。否则应该为安全起见而实施。即,即使程序员没有正确调用dispose方法,finalize也应该清理非托管资源。

比较示例:来自msdn

http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx& http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx

答案 3 :(得分:0)

只是为了完成IDisposable实现模式,通常为您的类包含一个终结器(析构函数),它调用Dispose()方法(传递false)。这充当故障保护机制,如果类的使用者无法调用Dispose(),则允许您处置非托管对象。

    ~MyClass() 
    {
        Dispose(false);
    }