(.net) CriticalFinalizerObject - 它到底有什么作用?

发布于 2024-07-27 23:50:06 字数 150 浏览 6 评论 0原文

我对这个类的理解是,当您想确保调用该类的终结器(析构函数)时应该使用它,但从我所做的一些测试来看,这似乎并不正确。 如果它不能确保调用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

2024-08-03 23:50:06

从我所做的一些测试来看,这似乎不是真的。

.Net 中的终结器是非确定性的。这意味着无法保证何时确切地调用终结器。 仅仅因为对象超出范围甚至被释放,并不意味着终结器将立即被调用。 垃圾收集器将在未来某个未知的时间处理它。

from a couple of tests I did, it doesn't seem to be true.

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.

暮色兮凉城 2024-08-03 23:50:06

如果您确实需要在程序按 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.

鹤舞 2024-08-03 23:50:06

Finalize() 方法和 Dispose() 方法是不同的东西。

默认情况下,永远不会调用Dispose。 您必须自己从 Finalize 方法中调用它。 请考虑以下事项(为简洁起见,忽略此处正确的完成/处置模式中的明显失败):

public class Foo : IDisposable
{
    public void Dispose() 
    {
        // NOP
    }

    ~Foo()
    {
        Dispose();
    } 
}

The Finalize() method and Dispose() method are different things.

By default, Dispose would never be called. You would have to call it yourself from the Finalize method. Consider the following (ignoring the obvious failures in a proper finalize/dispose pattern here, for brevity):

public class Foo : IDisposable
{
    public void Dispose() 
    {
        // NOP
    }

    ~Foo()
    {
        Dispose();
    } 
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文