我有一个名为DatabaseHelper的类,它包装了一个DbConnection.为using语句设置此类的正确方法是什么?我已经实现了IDisposible,但我不确定我应该何时何地调用Connection.Close()或Connection.Dispose().
当我在我自己的Dispose()方法中调用Connection.Dispose()时,我有时会从我的DbConnection对象中获取SocketException.我认为这是因为旧的连接处于打开状态,但没有附加到异常的详细信息,所以我无法确定.
从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).