Reputation: 417
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);
}
Upvotes: 11
Views: 9407
Reputation: 941455
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.
This answer is getting dated, I need to edit to point out that the rules changed for .NETCore (aka .NET 5.0 and up). In the legacy framework, finalizers were called when the AppDomain was getting unloaded. Most typically at program termination. AppDomains however became unsupported in .NETCore, along with it is the loss of guarantee that finalizers are getting called.
Upvotes: 9
Reputation: 564413
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.
Upvotes: 10
Reputation: 19937
In 2023, when terminating a .NET
application, finalizers are (most likely) never called, as stated on MSDN:
.NET 5 (including .NET Core) or a later version: There's no output, because this implementation of .NET doesn't call finalizers when the application terminates.
Sure most of us are using .NET 5
or later at this point. Thus, don't rely on this behavior unless you plan to stick with .NET Framework
or running some non-Windows compatible .NET
implementation (e.g. some cloud provided Linux
version).
Instead, use IDisposable
as some have sugggested here.
Upvotes: 3
Reputation: 108957
Finalizer is called by garbage collector and the garbage collection is not a predictable process hence it is not very reliable. You need to figure out other means to dispose your resources.
Upvotes: 2