【问题标题】:InvalidOperationException Updating TextBlock [duplicate]InvalidOperationException 更新 TextBlock [重复]
【发布时间】:2013-03-15 08:16:55
【问题描述】:

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

正确的方法将不胜感激。

【问题讨论】:

  • 现在在哪一行得到异常?你确定不是scroller.ScrollToBottom()
  • chatBox.Inlines.Add(message) 抛出异常
  • 我不认为这是一个重复的问题,因为我已经在使用调度程序了。

标签: c# wpf


【解决方案1】:

Inline 类继承自 DispatcherObject,这意味着由该类创建的任何对象都与创建它们的线程相关联。从您的代码来看,AppendLineToChatBox 方法似乎被工作线程调用,并且工作线程还拥有 Inline 对象。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 2015-03-23
    • 2011-11-25
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    相关资源
    最近更新 更多