Jimmy
Jimmy

Reputation: 5241

Application.ThreadException: memory leak if not detached?

The reference page for Application.ThreadException says

Because this is a static event, you must detach your event handlers when your application is disposed, or memory leaks will result.

Notwithstanding the fact that the sample code on that very page does not detach the event handler, does it really leak if the event handler is not detached?

It seems the only time the handler should be detached is if the application shuts down. In that case, whether or not the handler is detached, all the memory used by the application will be freed anyway?

Upvotes: 10

Views: 884

Answers (2)

Allon Guralnek
Allon Guralnek

Reputation: 16131

It is probably very uncommon, but a WinForms application's Main() method could possibly, 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 will appear, unless the splash screen set the AbortStatup property to true. If you added an event handler to Application.ThreadException from within the splash screen, the instance of CancelableSplashScreen won't be garbage collected until the application terminates, which may be a considerable time later.

Upvotes: 9

casperOne
casperOne

Reputation: 74560

If you let the reference to the object go (assuming it's an instance method that is the event handler) then yes, there will be a leak; you won't be able to unsubscribe from the event (since you don't have the instance anymore) and the object will exist until the app domain ends (as that is the lifetime of static variables).

Upvotes: 2

Related Questions