当我实现 IDisposable 时,VS 会自动生成这些区域化过程:
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
End If
' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
' TODO: set large fields to null.
End If
Me.disposedValue = True
End Sub
' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
'Protected Overrides Sub Finalize()
' ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
' Dispose(False)
' MyBase.Finalize()
'End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
想象一下,我的班级有一个永远不会关闭/处置的一次性对象(来自 Process Class 的新流程),所以我想处置它在 Class 上实现 IDisposable ...
我的问题是:
在上面代码的哪一行我需要放一个
myProcess.Dispose()
?我有一些String和Integer变量不是一次性的,例如
dim myVar as string = "value"
,如果我在处置一次性对象时将这些 vars 的值设置为空值会更好吗?像这样的东西?:sub dispose() myProcess.Dispose() myvar = nothing end sub
我的类调用了一些 WinAPI 函数并且还覆盖了 WndProc 子来解析消息,我需要使用终结器或者我可以使用 SuppressFinalize?,如果我需要使用终结器......我需要做什么?只是我取消注释 Finalize 子,仅此而已?我不确定终结器的用途或何时以及如何使用它。
虽然我不确切知道实现 Dispose 方法的正确方法,但我正在以这种方式处理它,但肯定以一种或其他方式完全错误......:
#Region " Dispose "
''' <summary>
''' Disposes all the objects created by this class.
''' </summary>
Public Sub Dispose() _
Implements IDisposable.Dispose
' Process
p.Dispose()
' Public Properties
Me.mp3val_location = Nothing
Me.CheckFileExist = Nothing
' String variables
StandardError = Nothing
StandardOutput = Nothing
Info = Nothing
Warnings = Nothing
Errors = Nothing
Tags = Nothing
' RegEx variables
Info_RegEx = Nothing
Warning_RegEx = Nothing
Fixed_RegEx = Nothing
' EventArgs Variables
StartedArgs = Nothing
ExitedArgs = Nothing
GC.SuppressFinalize(Me)
End Sub
#End Region
更新
所以...简化令人困惑的 VS 生成的代码,使其对我的要求更加直观和友好,我应该像这样使用它吗?:
Public Class Test : Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Protected Overridable Sub Dispose(IsDisposing As Boolean)
Static IsBusy As Boolean ' To detect redundant calls.
If Not IsBusy AndAlso IsDisposing Then
' Dispose processes here...
' myProcess.Dispose()
End If
IsBusy = True
End Sub
End Class