When handling the dispose of your own class, such as something like:
Protected Overridable Sub Dispose(disposing As Boolean)
If Disposed = False Then
If disposing Then
...
End If
...
End If
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Protected Overrides Sub Finalize()
Dispose(False)
End Sub
Since we suppress finalize, should I be setting the generic values like string, integers to null values (I.E. vbnullstring for strings, for example) in the Dispose as well? Generally I have this to dispose of timers, but should I be suppressing finalize here or will it still be removed after some time when going out of scope.
Thanks!
It's important to understand what disposing a finalizing actually do. Disposing allows you to explicitly release unmanaged resources held by your object and also to dispose managed objects to allow them to do the same. Those resources need to be released before the memory occupied by an object can be reclaimed. If you dispose an object explicitly then the garbage collector can reclaim the object's memory on the first pass. If you don't dispose, the GC must finalize on the first pass and can't reclaim the memory until the second pass, thus making garbage collection less efficient.
If you don't set your object's fields to Nothing
when you dispose it then that will also slow down the reclamation of memory. In most cases, that's not a big deal. If your fields refer to objects that themselves occupy a large amount of memory though, it can be more of an issue. That's why the comments added automatically by the IDE specify that you should clear fields that might refer to large objects in the Dispose
method. Remember, setting a variable to Nothing
may not help in many cases but, as long as you're finished with the variable, it certainly won't hurt. If in doubt, null you field.