0

I have tried following other questions to add some content to a WPF textblock from worker threads by using the Dispatcher. I am using the following method:

private void AppendLineToChatBox(Inline message)
{        
    chatBox.Dispatcher.BeginInvoke(new Action(() =>
    {
        chatBox.Inlines.Add(message);
        chatBox.Inlines.Add("\n");
        scroller.ScrollToBottom();
    }));
}

with XAML:

<Grid Height="200" Width="300" HorizontalAlignment="Left">
    <ScrollViewer Name ="scroller">
        <TextBlock TextWrapping="Wrap" Background="White" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Name="chatBox" />
    </ScrollViewer>
</Grid>

When I call AppendLineToChatBox() from a background thread I am still getting the following exception:

System.InvalidOperationException was unhandled HResult=-2146233079
Message=The calling thread cannot access this object because a different thread owns it.

The correct method would be greatly appreciated.

CanCan
  • 119
  • 6

1 Answers1

1

The Inline class inherits from DispatcherObject, which means any objects that are created of this class are tied to the thread they are created on. From looking at your code, it looks like the AppendLineToChatBox method is being called by a worker thread, and the worker thread also owns the Inline object.

To solve this issue, you will need to construct the Inline object in the UI thread (e.g. the block of code in the BeginInvoke)

Flangus
  • 206
  • 1
  • 2