如何调用Application.Exit在一个非UI线程 [英] How to call Application.Exit on an non UI Thread
问题描述
我有一个UI设计的问题。
I have a UI design question.
我想退出应用程序,当它遇到一个非UI线程例外。
I would like to exit the application when it encounter an exception on a non-UI thread.
基本上,该事件是这样的:
Basically, the event goes like this:
主窗体 - >子的WinForm的的ShowDialog(MainThread) - >启动一个后台线程(的WorkerThread) - >时发生异常 - >显示的ErrorForm(的WorkerThread)
Main Form -> ShowDialog of sub WinForm (MainThread)-> Starts a background thread (WorkerThread) -> Exception occurs -> Show an ErrorForm (WorkerThread)
在上ErrorForm用户点击退出按钮,我想退出整个应用程序。然而,做以下不能正常工作
When the user click Exit button on the ErrorForm, i want to exit the entire application. However, doing the following call doesn't work.
Invoker.Invoke((Action)(() => { Application.Exit(); }), null);
调用者参考的主要形式SynchronizedContext。然而,由于MainThread仍在等待subWinForm返回其控制,它可能无法处理Application.Exit()。
The Invoker reference to the main form SynchronizedContext. However, since the MainThread is still waiting for the subWinForm to return its control, it probably can't handle the Application.Exit().
这将是一个更好的设计处理异常是由后台工作线程抛出?
What would be a better design to handle exception that is thrown by a background worker thread?
推荐答案
的取消后台工作并发送参数BackgroundWorker的RunWorkerCompletedEvent识别有异常。之后,调用 Application.Exit()
从这里就可以了。
Cancel the background worker and send an argument to the BackgroundWorker RunWorkerCompletedEvent to identify there is an exception. After that call the Application.Exit()
from there would be fine.
这篇关于如何调用Application.Exit在一个非UI线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!