显示来自线程的 MessageBox,就像它来自 C#/WPF 中的主线程一样
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19936652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Show MessageBox from thread as it were from the main thread in C#/WPF
提问by André Santaló
There is a thread which can throw an exception, and when does so it is caught, a certain message box is shown, and then the software closes.
有一个线程可以抛出异常,当它被捕获时,会显示一个特定的消息框,然后软件关闭。
However, the problem is that since it is not the program's main thread, when I show the message box, the program window remains free for the user to interact with. It does not lock the screen, unlike when the message box is shown above the main window. I want to avoid this.
然而,问题是,由于它不是程序的主线程,当我显示消息框时,程序窗口仍然可以供用户交互。它不会锁定屏幕,这与消息框显示在主窗口上方不同。我想避免这种情况。
I wanted to know what would be the best way to do this. Up to now, I thought of using some kind of thread communication (never used this in C#) to raise the message box from the main thread.
我想知道这样做的最佳方法是什么。到目前为止,我想到了使用某种线程通信(在 C# 中从未使用过)从主线程中提升消息框。
Raising the thread:
提高线程:
Thread thread = new Thread(new ThreadStart(MyClass.MyMethod));
thread.IsBackground = true;
thread.Start();
The capture of the exception is in various parts of MyMethod. It is a thread that keeps running nonstop in a loop since the start of the program. The cause of the exception would be a network error.
异常的捕获在MyMethod. 它是一个从程序开始就不停地循环运行的线程。异常的原因可能是网络错误。
回答by Mike Perrenoud
You can probably just invoke it on the Dispatcher:
您可能只需在以下位置调用它Dispatcher:
Application.Current.Dispatcher.Invoke(() => MessageBox.Show(...));
回答by Rudis
You can also use SynchronizationContext(http://msdn.microsoft.com/library/system.threading.synchronizationcontext(v=vs.110).aspx)
您还可以使用SynchronizationContext(http://msdn.microsoft.com/library/system.threading.synchronizationcontext(v=vs.110).aspx)

