我尝试过使用Dispatcher从工作线程向WPF文本块添加一些内容的其他问题。我使用以下方法:
private void AppendLineToChatBox(Inline message)
{
chatBox.Dispatcher.BeginInvoke(new Action(() =>
{
chatBox.Inlines.Add(message);
chatBox.Inlines.Add("\n");
scroller.ScrollToBottom();
}));
}
使用XAML:
<Grid Height="200" Width="300" HorizontalAlignment="Left">
<ScrollViewer Name ="scroller">
<TextBlock TextWrapping="Wrap" Background="White" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Name="chatBox" />
</ScrollViewer>
</Grid>
当我从后台线程调用AppendLineToChatBox()时,我仍然遇到以下异常:
System.InvalidOperationException未处理HResult = -2146233079
Message =调用线程无法访问此对象,因为a 不同的线程拥有它。
非常感谢正确的方法。
答案 0 :(得分:1)
Inline类继承自DispatcherObject,这意味着由此类创建的任何对象都与创建它们的线程相关联。从查看代码看,工作线程调用AppendLineToChatBox方法,工作线程也拥有Inline对象。
要解决此问题,您需要在UI线程中构造Inline对象(例如BeginInvoke中的代码块)