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

2023-09-03 03:32:05 作者:愿时光厚待我爱人

我有一个WPF应用程序中,一个线程检查一定的价值。在某些情况下,我将展示以显示消息弹出窗口。当我在线程创建这个弹出窗口,一个例外是通过弹出窗口的构造函数抛出:

  

调用线程必须STA,因为许多UI组件都需要这个。的

我如何解决这个问题?

这是我的$ C $下创建的弹出窗口:

  //使用的System.Threading;
//使用System.Windows.Threading程序;
螺纹Messagethread =新主题(新的ThreadStart(委托()
{
    的DispatcherOperation DispacherOP =
        frmMassenger.Dispatcher.BeginInvoke(
            DispatcherPriority.Normal,
            新的行动(委托()
            {
                frmMassenger.Show();
            }));
}));
Messagethread.Start();
 

解决方案

绝对的 调度 的仅仅是做一些事情的方式(在特定的线程)当我们与多线程在WPF工作!

不过,与调度员的工作,我们必须知道两件事情:

有太多的方式来使用调度像Dispatcher_Operation, [window.dispatcher]或等。 我们要的 在应用程序的主线程调用调度 的(即线程必须STA线程)

因此,例如:如果我们想表现出其他的的窗口[WPF] 的在另一个线程,我们可以使用这个code:

  Frmexample frmexample =新Frmexample();
            Frmexample .Dispatcher.BeginInvoke
                (System.Windows.Threading.DispatcherPriority.Normal,
                (动作)(()=>
                {
                    frmexample.Show();
                    // ---或做ü希望与形式的任何事情
                }
                ));
 
eclipse 开发Android的ui组件尺寸颜色属性修改不了

提示: 记住我们不能访问从出调度的任何字段或属性,因此使用在刀刃

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();

解决方案

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:

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)

So for example: if we want show other window[wpf] in another thread, we can use this code:

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

Tip: Remember We cant access any fields or properties from out dispatcher, so use that wisely