“调用线程必须是 STA,因为许多 UI 组件都需要这个”在线程中创建WPF弹出窗口时出错
我有一个 WPF 应用程序,其中线程检查某些值。在某些情况下,我会显示一个弹出窗口来显示消息。当我在线程中创建这个弹出窗口时,弹出窗口的构造函数抛出异常:
“调用线程必须是 STA,因为许多 UI 组件都需要它。”
如何解决此错误?
这是我创建弹出窗口的代码:
// 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();
I have a WPF application in which a thread checks some value. In certain cases, I show a pop-up Window
in 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:
"The calling thread must be STA, because many UI components require this."
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于您尝试在其中启动 GUI 元素的线程,您需要在启动它之前将线程的单元状态设置为 STA。
例子:
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 BEFORE you start it.
Example:
绝对
Dispatcher
是我们在 WPF 中使用多线程时执行某些操作(在特定线程中)的唯一方法!但是为了使用 Dispatcher,我们必须知道两件事:
[window.dispatcher] 或等等。
在应用程序的主线程中调用调度程序
(该线程必须是 STA 线程)例如:窗口[wpf],我们可以使用以下代码:
提示:
记住 - 我们无法从调度程序访问任何字段或属性,因此请明智地使用
Absolutely
Dispatcher
is only way to do something (in specific Thread) when we work with multi-threading in WPF!But for work with Dispatcher we must know 2 things:
[window.dispatcher] or etc.
call dispatcher in the main thread of app
(that thread is must be STA thread)So for example: if we want show other window[wpf] in another thread, we can use this code:
Tip:
Remember - we can't access any fields or properties from out dispatcher, so use that wisely