WPF System.InvalidOperationException:调用线程无法访问此对象,因为另一个线程拥有它

Lie*_*oen 6 wpf multithreading

在我的Windows中,我有一个TextBox,我喜欢从另一个线程更新(文本属性).这样做时,我得到InvalidOperationException(参见标题).我在谷歌发现了不同的链接解释这一点,但我似乎仍然无法使它工作.

我试过的是这个:

Window1代码:

private static Window1 _myWindow;
private MessageQueueTemplate _messageQueueTemplate;
private const string LocalTemplateName = "LocalExamSessionAccessCodeMessageQueueTemplate";
private const string RemoteTemplateName = "RemoteExamSessionAccessCodeMessageQueueTemplate";

...
public Window1()
{
    InitializeComponent();
    _myWindow = this;
}

public static Window1 MyWindow
{
    get
    {
        return _myWindow;
    }
}

public void LogText(string text)
{
    informationTextBox.Text += text + Environment.NewLine;
}
...
Run Code Online (Sandbox Code Playgroud)

在另一个类(实际上是一个spring.NET Listener适配器,监听某个队列,在另一个线程中启动).

var thread = new Thread(
    new ThreadStart(
        delegate()
            {
                Window1.MyWindow.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(
                        delegate()
                            {
                                Window1.MyWindow.LogText(text);
                            }
                        ));
            }
        ));
Run Code Online (Sandbox Code Playgroud)

它不会引发错误,但在窗口1的LogText法文本没有被触发,因此文本没有更新.

所以基本上,我想从另一个线程中运行的另一个类更新这个TextBox组件.

Lie*_*oen 7

Window1.MyWindow.informationTextBox.Dispatcher.Invoke(
    DispatcherPriority.Normal,
    new Action(() => Window1.MyWindow.informationTextBox.Text += value));
Run Code Online (Sandbox Code Playgroud)