Can a static class know when it's being unloaded at application exit?

98 Views Asked by At

First, because I know everyone tries to help, I know this is not considered a good pattern. Second, yes, I know about the singleton pattern and use it often. Consider this more a question of "Can you" rather than "Should you".

That said, is there any way for a static class to be notified when the application is being shut down (or the console session has exited)?

Consider the following static class.

public static class Foo()
{
    static Foo()
    {
        // This is run the first time any static members are accessed
        StringOnFoo = LoadStringFromFile("mystring.txt");
    }

    public static string StringOnFoo{ get; set; }
}

Only thing I can think of is to create a class that implements an event and a destructor which calls it, then stuff that in a private static field of the static class and wire the event there.

What I don't know however is if it's safe to access event handlers in the destructor. Are they even still attached at that point?

0

There are 0 best solutions below