I have a class in C# where I want to close out some communication ports properly when my class is being disposed. However, the finalizer is never being called when I exit the program. Why is that? Am I doing something wrong?
I am calling the dispose manually which goes through and closes all communications. This is not fired either.
Here is the finalizer I am using:
~Power()
{
Dispose(false);
}
The term finalizer is mostly used in object-oriented and functional programming languages that use garbage collection, of which the archetype is Smalltalk. This is contrasted with a destructor, which is a method called for finalization in languages with deterministic object lifetimes, archetypically C++.
Finalizers (historically referred to as destructors) are used to perform any necessary final clean-up when a class instance is being collected by the garbage collector. In most cases, you can avoid writing a finalizer by using the System.
The Finalize method is used to perform cleanup operations on unmanaged resources held by the current object before the object is destroyed. The method is protected and therefore is accessible only through this class or through a derived class.
Finalize always runs before an object is garbage collected ( Option C ): The finalize method is like any method that can be called explicitly used if it is accessible.
The finalizer (which is what you're using here) is only called during the Finalization phase, which will happen during GC.
If you implement IDisposable correctly, this should never get called. I cover this in detail on my series on IDisposable.
That being said, if your "communication ports" are handled via managed classes, you shouldn't use a finalizer at all. This is adding overhead that does not help you whatsoever. Just implement IDisposable (properly), and let the managed wrappers around the port classes handle finalization if required.
If a tree falls in the forest with no one around to hear, does it make a sound? Make sure it does:
using System;
class Program {
static void Main(string[] args) {
new Test();
}
}
class Test {
~Test() { Console.Beep(); }
}
The finalizers of any objects left at program termination are called just before the process terminates. The only way this won't happen is when the process is rudely aborted. Environment.FailFast() for example.
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