Finalizer not called

折月煮酒 提交于 2019-12-05 09:50:44

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.

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.

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.

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