Home > Mobile >  C# Should you unsubscribe from static events inside static classes to prevent memory leaks?
C# Should you unsubscribe from static events inside static classes to prevent memory leaks?

Time:06-19

As the title suggests, I'm wondering whether I should unsubscribe from static events that I have subscribe to inside a static class. I've read about the memory leak issues that static events can cause but as far as I understand, once the application exits, all resources should be freed automatically. Does that count for the static events too or should I manually implement a way to unsubscribe from them before the application exits? The static event is going to be in a static class so the class' lifetime should be the same as the application's.

Thanks in advance!

P.S. I am aware that static events ought to be avoided whenever possible, but the event in question is Microsoft.Win32.SystemEvents.DisplaySettingsChanged.

CodePudding user response:

If the event usage is through the entire application life cycle then there is no need to worry about unsubscribing.

Once the application exit, the process ends and the memory is purged by the OS, so there is no memory leak after an application has ended.

  • Related