I have a UI design question.
I would like to exit the application when it encounter an exception on 开发者_如何学JAVAa non-UI thread.
Basically, the event goes like this:
Main Form -> ShowDialog of sub WinForm (MainThread)-> Starts a background thread (WorkerThread) -> Exception occurs -> Show an ErrorForm (WorkerThread)
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);
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?
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.
I know that invoking like this works in Silverlight:
Dispatcher.BeginInvoke(() => Application.Exit());
Or if there's no Dispatcher
for your WinForms classes:
Invoker.BeginInvoke(() => Application.Exit());
You had a lot of extra unnecessary code ((Action)
, null
, unnecessary brackets and parentheses). I don't think it would have stopped it from working correctly, but in any case, it's easier to read like this.
精彩评论