我对vb不太了解,并且从以前的程序员那里继承了一个应用程序。我被要求对代码运行Visual Studio分析以进行更改,因为该应用程序似乎引起了内存问题。我收到大量有关多次处置对象的消息,例如
警告CA2202在方法xxx'中可以多次放置对象'myConnection'。为避免生成System.ObjectDisposedException,您不应在对象上多次调用Dispose。
简单,将其包装在我认为的using块中。然后我发现myConnection用于try / catch
JumpUpAgain:
Try
myConnection.Open()
Catch ex As Exception
LogIt("EXCEPTION", "Connection Error: " & ex.Message)
myConnection.Close()
SqlConnection.ClearAllPools()
ConnectionString = Nothing
conn = Nothing
MySQLCmd = Nothing
myConnection = Nothing
Threading.Thread.Sleep(3000)
If ErrorLoopCounter = 5 Then
LogItDetail("Exception", "Database Connection Process failed after 5 re-tries")
If Not FailedFiles.Contains(InputFileName) Then FailedFiles.Add(InputFileName)
LogItDetail("DEBUG", "Added file to Failed Files for email")
FileProcessFailed = True
Throw
Else
ErrorLoopCounter += 1
End If
GoTo JumpUpAgain
End Try
在以后的代码中需要myConnection对象。 我将从catch中删除myConnection = Nothing,但是如果我在try / catch块之外放置了use / end using,如果应用程序命中了Throw,它将正确处理吗?
答案 0 :(得分:0)
使用代码块可确保即使发生错误,也可以关闭并处置db对象(与关闭同等重要)。您必须适应Try Catch,因为在块外定义的变量在块外不可见。
Private Sub OPCode2()
Dim dt As New DataTable()
'Keep your connections local
Using cn As New MySqlConnection("Your Connection String")
Using cmd As New MySqlCommand("Select * From YourTable", cn)
Try
cn.Open()
Using dr As MySqlDataReader = cmd.ExecuteReader
dt.Load(dr) 'or whatever you want to do with your connection
End Using
Catch
'Your logging logic here
End Try
End Using
End Using
End Sub