This is probably a really easy question, so sorry in advance if there are duplicates, but I haven't found anything about this specific problem yet.
I have a problem with coloring specific parts of text in a RichTextBox from a different thread. I want to append a line of text to the RichTextBox and at the same time color that line with a specified color. I was able to append text and color it, but haven't been able to do so from another thread, although I was able to append plain text from the Dispatcher.
Here is my code:
private void UpdateTextbox(string message, Brush color)
{
rtbOutput.Dispatcher.Invoke((Action)(() =>
{
rtbOutput.Selection.Select(rtbOutput.Document.ContentEnd, rtbOutput.Document.ContentEnd);
rtbOutput.Selection.Text = message;
rtbOutput.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, color);
})
);
}
When I try running it from another thread I get an error message telling me the object can't be accessed, because it belongs to another thread. How do I solve this?
Edit: Seems like the RichTextBox isn't the problem, but the Brush object is, because I can change the color just fine if I specify it inside the Invoke method, but not if I pass it as a parameter.
task.ContinueWith(() => { // code here }, TaskScheduler.FromCurrentSynchronizationContext());
– Rufus L