简体   繁体   English

从 C# 终结器调用静态方法

[英]Calling static methods from C# finalizer

Jeffrey Richter in his CLR via C# book (as seen online in the sample chapter Working with Types Requiring Special Cleanup ) indicates the following: Jeffrey Richter 在他的 CLR via C# 一书中(如在线示例章节“使用需要特殊清理的类型”中所见)指出以下内容:

Also, the CLR doesn't make any guarantees as to the order in which Finalize methods are called.此外,CLR 不保证调用 Finalize 方法的顺序。 So, you should avoid writing a Finalize method that accesses other objects whose type defines a Finalize method;因此,您应该避免编写一个 Finalize 方法来访问其类型定义了 Finalize 方法的其他对象; those other objects could have been finalized already.那些其他对象可能已经完成了。 However, it is perfectly OK to access value type instances or reference type objects that do not define a Finalize method.但是,访问未定义 Finalize 方法的值类型实例或引用类型对象是完全可以的。 You also need to be careful when calling static methods because these methods can internally access objects that have been finalized, causing the behavior of the static method to become unpredictable .调用静态方法时也需要小心,因为这些方法可以在内部访问已经终结的对象,导致静态方法的行为变得不可预测

I understand everything from the quote above, but the sentence which is in bold.我从上面的引文中理解了所有内容,但是粗体的句子。 How can a static method use finalized object internally if it can use only other static-members which reference to objects that can't be finalized because of their lifetime and why is it safe to call instance methods?如果静态方法只能使用其他静态成员,这些成员引用了由于生命周期而无法最终确定的对象,并且为什么调用实例方法是安全的,那么它如何在内部使用已完成的对象? Sorry, I may be wrong in my conclusions, so I'd be grateful for any explanations of the question.抱歉,我的结论可能有误,因此我将不胜感激对该问题的任何解释。 Thanks in advance.提前致谢。

For example we have two classes:例如我们有两个类:

sealed class B
{
    private A _a = new A();

    ~B()
    {
        B.ManipulateA(_a);
    }

    public static void ManipulateA(A a)
    {
        //manipulations with "A" object
    }
}

sealed class A
{
    ~A() { }
}

So if CLR doesn't make any guarantees as to the order in which Finalize methods are called , we should delete call to static method from B Finalizer, because our A object can be finalized already at the time when B Finalizer is called, and ManipulateA can try to access finalized object .所以如果CLR对调用Finalize方法的顺序不做任何保证,我们应该从B Finalizer中删除对静态方法的调用,因为我们的A对象可以在B Finalizer被调用的时候就已经完成了,而ManipulateA可以尝试访问finalized object

I think Jeffrey talks about something like this example.我认为杰弗里谈到了类似这个例子的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM