I have a UserControl that is added to my Main window. The Main code continuously receives TCP messages and interacts with the UserControl accordingly. One of the UserControl’s methods that is called by Main is AddMessage:
internal void AddMessage(Paragraph p)
{
if (txtViewer.Dispatcher.CheckAccess())
{
txtViewer.Document.Blocks.Add(p);
}
else
{
Dispatcher.Invoke(new Action(() =>
{
txtViewer.Document.Blocks.Add(p);
}
));
}
}
The line within Dispatcher.Invoke always throws an InvalidOperationException. I’ve looked around at similar issues, and most of them were cases where the Dispatcher wasn’t being used, so I don’t know why my code isn’t working. I suppose I’m using it incorrectly, or it may have something to do with the Paragraph object being passed between threads.
Thanks,
Jared
I had a similar problem in could not bind a DocumentViewer asynch as FlowDocument derived from Dispatcher. The UI cannot bind to an object that derives from Dispatcher on another thead. I had to serialize the FlowDocument to string (does not derive from dispatcher) using XamlWriter.Save then de-serialize in a Converter.