0

我尝试按照其他问题通过使用 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=调用线程无法访问此对象,因为不同的线程拥有它。

正确的方法将不胜感激。

4

1 回答 1

1

Inline 类继承自 DispatcherObject,这意味着由此类创建的任何对象都与创建它们的线程相关联。通过查看您的代码,看起来 AppendLineToChatBox 方法正在由工作线程调用,并且工作线程还拥有 Inline 对象。

要解决这个问题,您需要在 UI 线程中构造 Inline 对象(例如 BeginInvoke 中的代码块)

于 2013-03-15T00:16:55.550 回答