我試圖確保我不會在應用程序中留下任何鬆散的末端,並且擔心一些問題,但可能會從我的答案中得到答案。我已經「覆蓋」了一些功能,這樣我就可以嘗試儘可能保持所有資源的清潔和免費。所以在這個例子中,我有一個叫ExecuteReader
的函數,它正常地返回一個DbDataReader
,但我必須傳遞給它的是一個SQL字符串,而不是每次都重新創建一個DbCommand。我想確保即使我無法致電dbCommand.Dispose()
它實際上是這樣做的。任何和所有的幫助表示讚賞。此功能是否正確釋放資源?
Public Function ExecuteReader(ByVal strSQL As String) As DbDataReader
Dim dbCommand = _dbConnection.CreateCommand()
dbCommand.CommandText = strSQL
dbCommand.Prepare()
Return dbCommand.ExecuteReader()
End Function
我想用using
說法,但我記得看到一個線程如果有人說,他們認爲這是造成他們有在using
聲明回報問題。另外,我不確定這是否應該是社區wiki。如果應該的話,讓我知道。謝謝。
代碼更新:
這裏是我如何使用它的例子。
Public Sub RevertDatabase()
'This function can be used whenever all changes need to be undone, but was created'
'for saving the data as a .out file. It sets all changes back to their original value.'
'Set the data reader to all parts and columns that were changed.'
_dbReader = ExecuteReader("SELECT PART_ID, PART_PREV_VALUE, REPORT_COLUMN_NAME FROM REPORTS WHERE PART_PREV_VALUE NOT NULL")
'Create an instance of the Command class.'
Dim cmd = New Command()
While _dbReader.Read()
'For each part and columns that has been changed, set the values in the'
'new cmd variable and then update the value using the same function'
'that is used whenever a value is changed in the data grid view.'
cmd.CommandString = _dbReader("REPORT_COLUMN_NAME").ToString().Replace("_", " ")
cmd.Value = _dbReader("PART_PREV_VALUE").ToString()
cmd.ID = _dbReader("PART_ID").ToString()
UpdateValue(cmd)
End While
'Close the reader.'
_dbReader.Close()
End Sub
在這裏,我將_dbReader設置爲我從函數中得到的內容,並最終關閉了_dbReader。我不關閉連接,因爲每次查詢時都不打開它。這是一個SQLite數據庫,一次只能有一個用戶使用(小應用程序的可能性會越來越小),所以我不認爲有必要一直關閉和打開連接。也許我錯了,不確定。用這種方式,它可能可以清潔資源嗎?
檢查我更新的代碼。我想我應該說明我是如何使用它來查看是否仍然不安全。感謝你的回答。 – XstreamINsanity 2010-09-23 13:37:15
是的,在我發表了關於不需要打開和關閉它的帖子後,我想我會測試打開它需要多長時間,並且不需要很長時間,所以我也可以。我感謝您的答覆,並會盡力實施,無論我在哪裏使用它。 – XstreamINsanity 2010-09-23 14:21:28