Application.ThreadException: memory leak if not disconnected?

The page for Application.ThreadException says

Since this is a static event, you must disable the event handlers when the application is uninstalled or a memory leak occurs.

Despite the fact that the sample code on this page does not separate the event handler, does it really leak if the event handler is not disconnected?

It seems that the only time the handler needs to be disconnected, this application closes. In this case, regardless of whether the handler is disconnected, all the memory used by the application will still be freed?

+6
source share
2 answers

This is probably very rare, but the WinForms Main() method could for some reason look like this:

 static bool AbortStartup { get; set; } [STAThread] public static void Main() { Application.Run(new CancelableSplashScreen()); if (!AbortStartup) Application.Run(new MainWindow()); } 

When the splash screen closes, the main window appears if the splash screen does not close the AbortStatup property to true . If you added an event handler to Application.ThreadException from the pop-up screen, the instance of CancelableSplashScreen will not collect garbage until the application terminates, which may be much later.

+4
source

If you give a reference to the go object (assuming that it is an instance method that is the event handler), then yes, there will be a leak; you will not be able to unsubscribe from the event (since you no longer have an instance), and the object will exist until the application domain expires (since this is the lifetime of static variables).

+1
source

Source: https://habr.com/ru/post/899549/


All Articles