Finalizer not called

爱⌒轻易说出口 提交于 2020-01-02 04:35:12

问题


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);
}

回答1:


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.




回答2:


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.




回答3:


C# finalizers are not guaranteed to be called at any particular time. They should not be mistaken for C++ destructors.

If you want to guarantee predictable disposal, implement IDispose and instantiate your class in a using block:

using (Power power = new Power())
{
    //  blah blah
}

If a using block isn't practical, implement IDispose -- you've got to write a Dispose method that disposes of whatever resources you need to release; for all the exact requirements, see MSDN online -- and call Dispose() explicitly at the appropriate time. If you're multithreaded, that may require some sychronization code to ensure that it doesn't happen too soon.




回答4:


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.



来源:https://stackoverflow.com/questions/5200848/finalizer-not-called

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!