✅ ERROR: The calling thread cannot access this object because a different thread owns it.

Hey, I'm getting this error The calling thread cannot access this object because a different thread owns it. from the following method when trying to add a Run element to a RichTextBox

I've tried Googling a ton and even tried ChatGPT to see if it could fix it for me, all answers point to use chatRichTextBox.Dispatcher.Invoke but it still fails, any ideas?
private void AddChatMessage(string username, string message, System.Drawing.Color usernameColor)
{
    System.Windows.Media.Color mediaColor = System.Windows.Media.Color.FromArgb(usernameColor.A, usernameColor.R, usernameColor.G, usernameColor.B);

    var usernameRun = new Run(username)
    {
        Foreground = new SolidColorBrush(mediaColor),
        FontWeight = FontWeights.Bold
    };
    var messageRun = new Run(": " + message)
    {
        Foreground = Brushes.White
    };

    var paragraph = new Paragraph();
    paragraph.Inlines.Add(usernameRun);
    paragraph.Inlines.Add(messageRun);

    // Ensure the UI update is done on the UI thread
    chatRichTextBox.Dispatcher.Invoke(() =>
    {
        chatRichTextBox.Document.Blocks.Add(paragraph);
        chatRichTextBox.ScrollToEnd();
    });
}
Was this page helpful?