终结不叫 [英] Finalizer not called
问题描述
我在C#中的一类,我想正确地关闭了一些通信端口我的课被处置时。然而,终结永远不会被当我退出程序调用。这是为什么?难道我做错了什么?
我是手动调用的Dispose其中经过并关闭所有通信。这是不是要么解雇
下面是我使用的终结:
〜电源()
{
的Dispose(假);
}
终结(这是什么你用在这里)在最后定稿阶段,这将GC期间发生时才调用。
如果你正确地实现IDisposable,这不应该被调用。我管这个细节上我上了IDisposable 系列。
这虽这么说,如果你的通信端口通过托管类来处理,你不应该使用一个终结的。这是增加开销不帮你任何责任。只是实现IDisposable(正常),并让如果需要的端口类围绕托管的包装处理定稿。
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 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.
这篇关于终结不叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!