Search code examples
c#.netvisual-studio-2010memory-leakssystemevent

When should i unregister system events to prevent memoryleaks?


I am using systemevents like this:

            SystemEvents.SessionEnding += SystemEventsSessionEnding;

to detect when user shutsdown or log off, but i have read that i need to unregister this event to prevent memoryleaks and such.

When/Where should i do that?

I have seen that i can do that in SystemEvents.EventsThreadShutdown, this event will fire BEFORE the system events fires, and IF this is true, then this should be the place where i should unregister my systemevents?

Or should i do that in my mainforms FormClosing event? Will the FormClosing event get fired att all times?

Thank you!


Solution

  • If you need to be alerted when that event is fired throughout the lifetime of your application instance then no, you don't need to unregister it. If you have objects that go out of scope which subscribe to that event then they should unregister as the event object holds a reference to the subscriber, preventing it from being GC'd.