如何正确处理共享资源和SQL连接

时间:2012-10-02 13:08:21

标签: vb.net dispose idisposable sqlconnection asp.net-1.1

我有一个ASP.NET 1.1网站,流量相当大。我在这个网站项目中有一个类来处理我所有的数据库访问,称为DBWrapper:

Public Class dbWrapper
Implements IDisposable

' the private _connVSC2000 property is used for all methods that return scalar and DataType types
Private _connVSC2000 As SqlConnection
Private _connectionString As String
Private _disposed As Boolean = False

Sub New(ByVal connectionString As String)
    _connectionString = connectionString
    _connVSC2000 = New SqlConnection(connectionString)
    _connVSC2000.Open()
End Sub

Public Overloads Sub Dispose() Implements IDisposable.Dispose
    Dispose(True)
    GC.SuppressFinalize(Me)
End Sub

Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean)
    If Not _disposed Then
        'If _connVSC2000.State = ConnectionState.Open Then _connVSC2000.Close()
        If disposing Then
            _connVSC2000.Dispose()
        End If
    End If
    _disposed = True
End Sub

Protected Overrides Sub finalize()
    Dispose(False)
    MyBase.Finalize()
End Sub

' Actual database access functions removed as they are not relevant to the question.
end class

我还有一个类(实际上有几个),它有许多使用共享dbWrapper对象的共享函数:

Public Class SomeClass

Private Shared dbWrapper As New dbWrapper(ConfigurationSettings.AppSettings("VSCConnectionString"))

public shared Function SomeFunction()
    'function that utilizes the shared dbWrapper object.
end Function
End Class

我遇到的问题是,一段时间后,连接池会填满,因为连接没有及时释放。我的问题有三个:

是否正确实现了dbWrapper类中SQLConnection对象的处理?

在'SomeClass'中实现dbWrapper对象的处理的正确方法是什么,以确保dbWrapper对象以及SQLConnection对象被正确处理掉并且不会堵塞连接池? 完成后我是否需要显式调用SomeClass.Dispose,否则当它超出范围时会自动处理?

0 个答案:

没有答案