I am working on a bunch of classes in some pretty old code. Many implement the IDisposable
interface and the Dispose()
method. But from what I have read, any class implementing IDisposable
should always also implement Dispose(Boolean)
.
Even the code generated by Visual Basic to help implement IDisposable
suggest this (sorry about the VB..):
#Region "IDisposable Support"
Private mDisposed As Boolean
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not mDisposed 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
mDisposed = True
End Sub
' TODO: override Finalize() only if Dispose(disposing As Boolean) above has code to free unmanaged resources.
'Protected Overrides Sub Finalize()
' ' Do not change this code. Put cleanup code in Dispose(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)
' TODO: uncomment the following line if Finalize() is overridden above.
' GC.SuppressFinalize(Me)
End Sub
#End Region
It comes with a Dispose(Boolean)
and a Dispose()
method, while the Finalize()
method is commented, suggesting it is the only thing that is optional.
What I find confusing however is, if I don't implement the Finalize()
method, the Dispose(Boolean)
method seemingly becomes obsolete, as it will literally always be called with disposing == true
. From my understanding this would result in the exact same execution logic, apart from the method added on top of the stack.
Am I missing something or can I safely ditch Dispose(Boolean)
?
Aucun commentaire:
Enregistrer un commentaire