简体   繁体   中英

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:

Also, the CLR doesn't make any guarantees as to the order in which Finalize methods are called. So, you should avoid writing a Finalize method that accesses other objects whose type defines a Finalize method; 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. 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 .

I think Jeffrey talks about something like this example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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