简体   繁体   中英

How to avoid WPF Application not Responding when logging off

When trying to press the standard Windows 7 logoff button while my WPF app is running, I get "This program is preventing Windows from logging off". I would like to force it to close without having to press "Force log off".

Similarly, pressing "End Task" in the (applications) Task Manager causes it to become non-responsive rather than just close the program.

I have tried adding this to Window_Closing, but this doesn't seem to do it:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    Environment.Exit(0);
}

I'm new to WPF, but it seems to me that the window is not closing properly. How can I prevent the "program is preventing Windows from logging off" when executing the Windows logoff, or "Program is not responding" when killing it from task manager?

This should only be an issue if your application is not responding to the close events sent from Windows.

This will typically happen if you are executing code on the UI thread, which prevents it from responding to messages. As such, putting something in the closing events and similar will have no effect, as they won't be able to process until after your "work" finishes.

The proper way to handle this is to move your work onto background threads. This keeps the application responsive, which allows it to respond to the request from Windows to Close.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM