14

我有一个 WPF 应用程序,其中一个线程检查一些值。在某些情况下,我会显示一个弹出窗口Window以显示消息。当我在线程中创建这个弹出窗口时,弹出窗口的构造函数会抛出异常:

“调用线程必须是 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();
4

2 回答 2

14

对于您尝试在其中启动 GUI 元素的线程,您需要在启动它之前将线程的单元状态设置为 STA 。

例子:

myThread.SetApartmentState(ApartmentState.STA);
myThread.Start();
于 2010-04-17T04:21:41.493 回答
10

当我们在 WPF 中使用多线程时,绝对Dispatcher是做某事(在特定线程中)的唯一方法!

但是要使用 Dispatcher,我们必须知道两件事:

  1. 使用 Dispatcher 的方法太多,例如 Dispatcher_Operation 、 [window.dispatcher] 等。
  2. 我们必须call dispatcher in the main thread of app(该线程必须是 STA 线程)

例如:如果我们想在另一个线程中显示其他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
                }
                ));

提示: Remember - we can't access any fields or properties from out dispatcher, so use that wisely

于 2010-07-14T05:14:46.353 回答