I was working through an example and I saw this...
#if DEBUG
/// <summary>
/// Useful for ensuring that ViewModel objects are properly garbage collected.
/// </summary>
~ViewModelBase()
{
string msg = string.Format("{0} ({1}) ({2}) Finalized", this.GetType().Name, this.DisplayName, this.GetHashCode());
System.Diagnostics.Debug.WriteLine(msg);
}
#endif
I tried to Google it but couldn't get any results... I was just wondering what it means. Anyone know?
Thanks
It is the finalizer for the ViewModelBase class. It is called by the garbage collector before collection.
It is not really very useful because:
a) Garbage collection does really work and you do not need to test it.
b) It tells you nothing about your code when this gets called during normal execution, because for the most part the Garbage Collector just does its own thing and collects when it determines that there is memory pressure.
For the most part it is OK to not worry about the Garbage Collector - only worry about it when you have a real problem.
Also experience tells me - avoid using the finalizer since you are never sure what state the rest of your program will be in when it is called.
It's a finalizer (a special method that is invoked by the garbage collector). Finalizers are designed to dispose unmanaged resources owned by an type implementing IDisposable
even if its Dispose()
method is never called.
The reason the author of this class wrote that debug code isn't 100% clear, but such debugging code is usually just a means of saying "hey dummy, you forgot to call Dispose()
manually". It's a fairly common debugging aid (I've seen it in quite a lot of code), though I don't use it myself.
Sometimes an instance of a type holds precious resources and it's in your interest to call Dispose() as soon as you're finished with it. What the author's code is doing is saying "if I ever reach this Finalizer, you're failing to call Dispose() as soon as possible." It's not really what you'd use a Finalizer for in production code, though.
This is called a finalizer.
It's called by the garbage collector at an indeterminate point in time when the object is collected, on the GC thread.
They also have a performance hit.
In general, you will never write a finalizer.
Finalizers are used by classes that directly own native resources (unless they use SafeHandles, which they should), and for special debugging tricks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With