下面讨论的上述代码的原始参考在这里:
OracleConnection
我已经使用 Oracle 完成了以下操作,我认为它可以通过一些小的修改(例如 change等)与 MySQL 一起使用。您可以创建一个名为 ConnectionSpy 的类(见下文)。这是在 VB.Net 中,如果您愿意,您可以将代码转换为 C#。
Imports System
Imports System.Data
Imports Oracle.DataAccess.Client
Imports System.Diagnostics
Imports System.IO
Public Class ConnectionSpy
Dim con As OracleConnection
Dim st As StackTrace
Dim handler As StateChangeEventHandler
Dim logfileName As String
Public Sub New(ByVal con As OracleConnection, ByVal st As StackTrace, ByVal logfileName As String)
If (logfileName Is Nothing Or logfileName.Trim().Length() = 0) Then
Throw New ArgumentException("The logfileName cannot be null or empty", logfileName)
End If
Me.logfileName = logfileName
Me.st = st
'latch on to the connection
Me.con = con
handler = AddressOf StateChange
AddHandler con.StateChange, handler
'substitute the spy's finalizer for the
'connection's
GC.SuppressFinalize(con)
End Sub
Public Sub StateChange(ByVal sender As Object, ByVal args As System.Data.StateChangeEventArgs)
If args.CurrentState = ConnectionState.Closed Then
'detach the spy object and let it float away into space
'if the connection and the spy are already in the FReachable queue
'GC.SuppressFinalize doesn't do anyting.
GC.SuppressFinalize(Me)
RemoveHandler con.StateChange, handler
con = Nothing
st = Nothing
End If
End Sub
Protected Overrides Sub Finalize()
'if we got here then the connection was not closed.
Using stream As FileStream = New FileStream( _
logfileName, _
FileMode.Append, _
FileAccess.Write, _
FileShare.Write)
Using sw As StreamWriter = New StreamWriter(stream)
Dim text As String = _
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") & _
": WARNING: Open Connection is being Garbage Collected" & _
Environment.NewLine & "The connection was initially opened " & st.ToString()
sw.WriteLine(text)
sw.Flush()
RemoveHandler con.StateChange, handler
'clean up the connection
con.Dispose()
End Using
End Using
End Sub
End Class
然后,在您的 web.config/app.config 中,您可以添加如下部分:
<configuration>
<appSettings>
<!--
if you need to track connections that are not being closed, set
UseConnectionSpy to "true". If you use the connection spy, a log
will be created (the logfile can be specified with the ConnectionSpyLog
parameter) which will give you a stack trace of each code location
where a connection was not closed
-->
<add key="UseConnectionSpy" value="true"/>
<add key="ConnectionSpyLog" value="c:\\log\\connectionspy.log"/>
</appSettings>
</configuration>
然后,无论您在代码中创建数据库连接的何处,都可以执行此操作(见下文)。该mConnection
变量将代表您的 MySQL 连接,当您到达这一点时,您已经创建了该连接。
If ConfigurationManager.AppSettings("UseConnectionSpy") = "true" Then
Dim st As StackTrace = New StackTrace(True)
Dim sl As ConnectionSpy = New ConnectionSpy(mConnection, st, _
ConfigurationManager.AppSettings("ConnectionSpyLog"))
End If
因此,如果您有任何连接在关闭之前被垃圾回收,则会在日志文件中报告。我在一些应用程序中使用了这种技术并且效果很好。
您需要做的是为您的 MySQL 数据库连接创建一个包装类,您可以将上述代码放在适当的位置以跟踪连接。或者,您可以将上述调用添加到您创建连接的任何位置。包装类虽然有点干净(这就是我们所做的)