WPF Dispatcher.Invoke'挂'Dispatcher、WPF、Invoke

2023-09-03 05:42:54 作者:继续,微笑つ

我有一个有点复杂WPF应用程序,这似乎是'挂'或试图使用调度调用UI线程调用时被陷在一个等待呼叫。

一般过程如下:

处理click事件上的按钮 创建一个新的线程(STA)的:创建的presenter和用户界面的新实例,然后调用该方法的断开 断开,然后将所调用UI属性的名称 的制定者名称,然后采用下列code设置该属性:

 
    如果(this.Dispatcher.Thread!= Thread.CurrentThread)
    {
        this.Dispatcher.Invoke(DispatcherPriority.Normal,(的ThreadStart)委托{
            this.Name =价值; //调用同一个二传手,但是在UI线程
        });
        返回;
    }

    的SetValue(nameProperty,价值); //我也尝试了成员变量和直接设置textbox.text财产。
 

我的问题是,当调度调用方法被调用似乎挂起每一次,和调用堆栈表示其处于休眠,等待或调用实现内加入。

那么,是不是我做错了,我很想念,很明显与否,或者是有要求传达给UI线程此属性(和其他)设置一个更好的办法?

编辑:解决的办法是打电话System.Windows.Threading.Dispatcher.Run()在线程的代表结束时(例如,​​其中正在执行的工作) - 感谢所有谁帮助

解决方案

您说您要创建一个新的STA线程,是调度员这个新的线程运行?

我是从this.Dispatcher.Thread!= Thread.CurrentThread,你希望它是一个不同的调度员获得。确保其运行否则它不会处理它的队列中。

WPF Dispatcher详解

I have a somewhat complex WPF application which seems to be 'hanging' or getting stuck in a Wait call when trying to use the dispatcher to invoke a call on the UI thread.

The general process is:

Handle the click event on a button Create a new thread (STA) which: creates a new instance of the presenter and UI, then calls the method Disconnect Disconnect then sets a property on the UI called Name The setter for Name then uses the following code to set the property:


    if(this.Dispatcher.Thread != Thread.CurrentThread)
    {
        this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate{
            this.Name = value; // Call same setter, but on the UI thread
        });
        return;
    }

    SetValue(nameProperty, value); // I have also tried a member variable and setting the textbox.text property directly.

My problem is that when the dispatcher invoke method is called it seems to hang every single time, and the callstack indicates that its in a sleep, wait or join within the Invoke implementation.

So, is there something I am doing wrong which I am missing, obvious or not, or is there a better way of calling across to the UI thread to set this property (and others)?

Edit: The solution was to call System.Windows.Threading.Dispatcher.Run() at the end of the thread delegate (e.g. where the work was being performed) - Thanks to all who helped.

解决方案

You say you are creating a new STA thread, is the dispatcher on this new thread running?

I'm getting from "this.Dispatcher.Thread != Thread.CurrentThread" that you expect it to be a different dispatcher. Make sure that its running otherwise it wont process its queue.