(.net) CriticalFinalizerObject - 它到底有什么作用?
我对这个类的理解是,当您想确保调用该类的终结器(析构函数)时应该使用它,但从我所做的一些测试来看,这似乎并不正确。 如果它不能确保调用 dispose 方法,是否还有其他方法可以做到这一点? 例如,如果我想确保运行某些代码来结束我的对象,即使我通过任务管理器或其他方式关闭我的程序?
My understanding about this class is that you should use it when you want to be sure that the Finalizer (destructor) of the class is called, but from a couple of tests I did, it doesn't seem to be true. If it does not make sure that the dispose method is called, is there any other way of doing it? For example, if I want to make sure that some code is run to end my object, even if I close my program via Task Manager or something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
克里斯布鲁姆以一种我不确定是否能被超越的方式解释了这个话题。 :)
Chris Brumme has explained this topic in a way I'm not sure could ever be topped. :)
.Net 中的终结器是非确定性的。这意味着无法保证何时确切地调用终结器。 仅仅因为对象超出范围甚至被释放,并不意味着终结器将立即被调用。 垃圾收集器将在未来某个未知的时间处理它。
Finalizers in .Net are non-deterministic. That means there's no guarantee exactly when the finalizer will be called. Just because an object went out of scope or even was disposed, doesn't mean the finalizer will be called right away. The garbage collector will get around to it at some unknown time in the future.
如果您确实需要在程序按 Ctrl+Alt+Del'd 时运行代码,我认为除了使用一个单独的程序来监视第一个程序的状态之外,没有其他方法了。 如果您确实需要那么多架构,我认为您会希望使用一个服务和一些客户端应用程序,或者一对或多个服务。
不过,这是假设您已经研究过应用程序事件。 如果还没有,请查看此概述。
编辑可能比该概述更好的是应用程序退出事件。
If you really need code to run when when your program is Ctrl+Alt+Del'd, I don't think there's any other way than to have a separate program that monitors the first's state. If you really need that much architecture, I think you'd want to be using a service and some client apps, or a pair or services.
This is assuming, though, that you've already looked into the Application events. If you haven't, check out this overview.
EDIT Better than that overview, probably, is the ApplicationExit event.
Finalize()
方法和Dispose()
方法是不同的东西。默认情况下,永远不会调用
Dispose
。 您必须自己从Finalize
方法中调用它。 请考虑以下事项(为简洁起见,忽略此处正确的完成/处置模式中的明显失败):The
Finalize()
method andDispose()
method are different things.By default,
Dispose
would never be called. You would have to call it yourself from theFinalize
method. Consider the following (ignoring the obvious failures in a proper finalize/dispose pattern here, for brevity):