WPF Application Shutdown on Windows 7 x64

3 02 2012

In WPF applications, the Application.Exit event is not (reliably) called – at least on Windows 7 x64 – when the user logs off from or shuts down or restarts the Windows machine. I found that my Application_Exit handler which performs important cleanup was not called.

I tried to remedy this first by hooking into the SystemEvents.SessionEnding event and calling Application.Shutdown from there. After doing this, I found that my Application_Exit handler was called, but then the process seemed to be killed in the middle of the shutdown processing (log output stopped suddenly).

Then I removed the SystemEvents.SessionEnding event handler again and tried to override the Application.OnSessionEnding virtual method. This resulted in the same behavior. The Application_Exit handler was sometimes called, sometimes not, but when it was called, the process died during shutdown processing.

I finally solved this by overwriting the Application.OnSessionEnding method, calling the base class implementation first, then setting SessionEndingCancelEventArgs.Cancel=true to avoid my process being killed by the OS, and finally explicitly calling Application.Shutdown to initiate the shutdown process. The end result is a clean application shutdown while Windows shows the „Application not responding“ screen for several seconds while my application shuts down.

Here’s the code:

public partial class App : Application
  protected override void OnSessionEnding(SessionEndingCancelEventArgs e)

    // Cancel application shutdown to prevent Windows 7 killing
    // the process
    e.Cancel = true;

    // Terminate myself



One response

3 02 2012

Very good post, thx for the information.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:


Du kommentierst mit Deinem WordPress.com-Konto. Abmelden /  Ändern )

Google Foto

Du kommentierst mit Deinem Google-Konto. Abmelden /  Ändern )


Du kommentierst mit Deinem Twitter-Konto. Abmelden /  Ändern )


Du kommentierst mit Deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s

%d Bloggern gefällt das: