Search code examples
c#wpfshutdown

Why does my C# WPF program keep executing lines after Application.Shutdown()?


Here's a snippet of code where I pop up a simple dialog ("chooser"). Depending on the user's input, the application might terminate.

    DPChooser chooser = new DPChooser(dataProvider);
    if (chooser.ShowDialog() == false)
        Application.Current.Shutdown(0);
    else
        ApplicationContext.Current.InitializeDataProviderAPI(chooser.DataProvider);
    }

    // more code continues here
    // THE PROBLEM:
    //     Even when Shutdown() above is called,
    //     the execution continues proceeding past here!

I've run it in a debugger, so I know that the if is evaluating to false, and I know that Shutdown() is being called.

So why doesn't it shut down?

Note: it's not a threading thing, I think. I'm not yet starting anything on other threads. Even if threading was involved, I'd still not expect the code in this thread to keep proceeding past Shutdown().


Solution

  • Shutdown stops the Dispatcher processing, and closes the application as far as WPF is concerned, but doesn't actually kill the current thread.

    In your case, you need to prevent code beyond that call from running. A simple return will suffice:

     if (chooser.ShowDialog() == false)
     {
         Application.Current.Shutdown(0);
         return;
     }
     else { //...