Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

wpf

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().

like image 444
Grant Birchmeier Avatar asked Dec 15 '11 22:12

Grant Birchmeier


2 Answers

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 { //...
like image 154
Reed Copsey Avatar answered Nov 10 '22 00:11

Reed Copsey


It doesn't Terminate your process instantly, its a controlled shutdown.

if you want ( not recommended ) to kill instantly

Process.GetCurrentProcess().Kill();
like image 21
Keith Nicholas Avatar answered Nov 10 '22 01:11

Keith Nicholas