0

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?

Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286
  • Actually, the standard says that it is run before any members are accessed. – Hogan Aug 03 '15 at 20:45
  • Tie into the application l.exit event and notify the class – Brandon Seydel Aug 03 '15 at 20:46
  • @Brandon, can't do that. Application is part of PresentationFramework which isn't referenced by this. This is in our core libraries that can be used for any type of application. – Mark A. Donohoe Aug 03 '15 at 20:52
  • @Hogan, can you show me where that standard is? Add a link? – Mark A. Donohoe Aug 03 '15 at 20:52
  • https://msdn.microsoft.com/en-us/library/k9x6w0hc.aspx – Hogan Aug 03 '15 at 20:54
  • also here (where it says you can use one of these) https://msdn.microsoft.com/en-us/library/79b3xss3.aspx – Hogan Aug 03 '15 at 20:56
  • 1
    To your question *if it's safe to access event handlers in the destructor* ... I wouldn't do so, since accessing event handler in finalizer would give another life to the object and so it will bypass GC in next collection (in case the object is already in dead state and ready to be collected, it will get resurrected). – Rahul Aug 03 '15 at 21:05
  • I just said that as a general statement. You would probably literally use appdomain.currentdomain events. – Brandon Seydel Aug 04 '15 at 11:45

0 Answers0