Application.Current.Shutdown() doesn't
Asked Answered
E

3

7

Title's about it. WPF app with some WCF stuff for IPC. I call Application.Current.Shutdown() and the app continues on happily. I thought Shutdown was supposed to be unstoppable.

Perhaps because it's being called from a background thread? Do I need to do some dispatcher fiddling?

Epicurus answered 8/12, 2009 at 14:38 Comment(0)
B
14

You get an exception when I call Application.Current.Shutdown in any thread other than the main one, so I'd assume you where using "dispatcher fiddling" properly already.

In any case, this compiles and quits an application, so if the dispatcher bit doesn't look like what you have you could sling it in:

ThreadStart ts = delegate()
    {
        Dispatcher.BeginInvoke((Action)delegate()
        {
            Application.Current.Shutdown();
        });
     };
 Thread t = new Thread(ts);
 t.Start();
Benjie answered 8/12, 2009 at 16:47 Comment(3)
I was trying to figure this out and this seems to work. Is there any explanation for how wrapping a dispatcher call in a thread makes it happy?Gleeman
Some classes uses threads that does not run on background. And Shutdown usually kills only background threads automatically. So you should try to make sure to dispose any variables that uses a class that uses threading before exiting.Spacious
Note that this seems to refer to Application.Current.Dispatcher, not System.Windows.Threading.Dispatcher.Alicaalicante
D
12

In my experience all threads have to either be terminated explicitly or be marked as background threads in order for the application to close.

Here is an example of kicking off a read thread in the background:

_readThread = new Thread(new ThreadStart(ReadThread));
_readThread.Name = "Receiver";
_readThread.Priority = ThreadPriority.Highest;
_readThread.IsBackground = true;
_readThread.Start();

The IsBackground property is the key. Without that being set, the thread won't terminate on when you call Shutdown.

Dog answered 8/12, 2009 at 14:51 Comment(2)
The app closes normally through other means though.Epicurus
Thanks a bunch for this comment, it saved me some major head ache trying to figure out why my application wasn't exiting completely.Carmody
R
2

I only experience Application.Current.Shutdown not working when I'm running from Visual Studio. Within Visual Studio (at least the 2010 version I'm using) Application.Current.Shutdown doesn't do a thing. If I single step through it executes this line and then continues. If I run the program (as an .exe) from Windows Explorer then Application.Current.Shutdown works fine.

There is probably an explanation for this since during debug other threads are active, but I can't explain it.

Ricard answered 7/7, 2015 at 1:25 Comment(2)
Yea, same here, but it really messes with my debugging.Smut
Changes are that the application is actually crashing when the debugger is not attached.Laurettalaurette

© 2022 - 2024 — McMap. All rights reserved.