"调用线程必须是STA,因为在线程中创建WPF弹出窗口时,许多UI组件都需要这个"错误

Rev*_*Rev 14 .net wpf multithreading dispatcher

我有一个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();
Run Code Online (Sandbox Code Playgroud)

Bri*_*ndy 14

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

例:

myThread.SetApartmentState(ApartmentState.STA);
myThread.Start();
Run Code Online (Sandbox Code Playgroud)

  • @Rev:可能你有2个问题.线程STA和调度程序.如果您需要有关调度员的帮助,请告诉我,我可以告诉您如何操作. (2认同)

Rev*_*Rev 9

Dispatcher当我们在WPF中使用多线程时,绝对只能做某事(在特定的线程中)!

但是对于与Dispatcher一起工作,我们必须知道两件事:

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

例如:如果我们想在另一个线程中显示其他窗口[wpf],我们可以使用以下代码:

Frmexample frmexample = new Frmexample();
            Frmexample .Dispatcher.BeginInvoke
                (System.Windows.Threading.DispatcherPriority.Normal,
                (Action)(() =>
                {
                    frmexample.Show();
                    //---or do any thing you want with that form
                }
                ));
Run Code Online (Sandbox Code Playgroud)

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