.net 在线程中创建WPF弹出窗口时出现“调用线程必须是STA,因为很多UI组件都需要这个”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2657212/
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
"The calling thread must be STA, because many UI components require this" error when creating a WPF pop-up Window in thread
提问by Rev
I have a WPF application in which a thread checks some value. In certain cases, I show a pop-up Windowin order to display a message. When I create this pop-up window in the thread, an exception is thrown by the pop-up window's constructor:
我有一个 WPF 应用程序,其中一个线程检查一些值。在某些情况下,我会显示一个弹出窗口Window以显示消息。当我在线程中创建这个弹出窗口时,弹出窗口的构造函数抛出一个异常:
"The calling thread must be STA, because many UI components require this."
“调用线程必须是 STA,因为许多 UI 组件都需要它。”
How do I resolve this error?
如何解决此错误?
This is my code for creating the pop-up window:
这是我创建弹出窗口的代码:
// using System.Threading;
// using System.Windows.Threading;
Thread Messagethread = new Thread(new ThreadStart(delegate()
{
DispatcherOperation DispacherOP =
frmMassenger.Dispatcher.BeginInvoke(
DispatcherPriority.Normal,
new Action(delegate()
{
frmMassenger.Show();
}));
}));
Messagethread.Start();
采纳答案by Rev
Absolutely Dispatcheris only way to do something (in specific Thread) when we work with multi-threading in WPF!
Dispatcher当我们在 WPF 中使用多线程时,绝对是做某事(在特定线程中)的唯一方法!
But for work with Dispatcher we must know 2 things:
但是为了与 Dispatcher 一起工作,我们必须知道两件事:
- Too many way to use Dispatcher like Dispatcher_Operation , [window.dispatcher] or etc.
- We must
call dispatcher in the main thread of app(that thread is must be STA thread)
- 使用 Dispatcher 的方法太多了,例如 Dispatcher_Operation 、 [window.dispatcher] 等。
- 我们必须
call dispatcher in the main thread of app(那个线程必须是 STA 线程)
So for example:if we want show other window[wpf]in another thread, we can use this code:
例如:如果我们想在另一个线程中显示其他window[wpf],我们可以使用以下代码:
Frmexample frmexample = new Frmexample();
frmexample .Dispatcher.BeginInvoke //Updated the variable name
(System.Windows.Threading.DispatcherPriority.Normal,
(Action)(() =>
{
frmexample.Show();
//---or do any thing you want with that form
}
));
Tip:Remember - we can't access any fields or properties from out dispatcher, so use that wisely
提示:Remember - we can't access any fields or properties from out dispatcher, so use that wisely
回答by Brian R. Bondy
For the thread that you're trying to start the GUI element in, you need to set the apartment state of the thread to STA BEFOREyou start it.
对于您尝试在其中启动 GUI 元素的线程,您需要在启动它之前将线程的单元状态设置为 STA 。
Example:
例子:
myThread.SetApartmentState(ApartmentState.STA);
myThread.Start();

