在我的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;
}
...
在另一个类中(实际上是Spring.NET监听器适配器,监听特定队列,在另一个线程中启动)。
var thread = new Thread(
new ThreadStart(
delegate()
{
Window1.MyWindow.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
Window1.MyWindow.LogText(text);
}
));
}
));
它不会抛出错误,但是Window1中LogText方法中的文本没有被触发,因此文本没有更新。
所以基本上,我想从另一个运行在另一个线程中的类中更新这个TextBox组件。
Dispatcher
是答案-但我们无法确定您在显示的代码中做错了什么。 - Jon Skeet