开发者

Finalizer not called

I have a class in C# where I want to c开发者_运维百科lose 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 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜