How to avoid WPF Application not Responding when logging off

安稳与你 提交于 2019-12-24 23:23:23

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/28866161/how-to-avoid-wpf-application-not-responding-when-logging-off

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!