Shaked Dahan
Shaked Dahan

Reputation: 402

The calling thread cannot access this object because a different thread owns it, even when using the dispatcher

I have a Paragraph object that I try to access from a different thread than it was created on, before posting my question here I searched for a solution online and I found the "Dispatcher" solution, which did not work for me, somehow.

Here's the code:

Run r = new Run((string)name + Environment.NewLine);
r.Foreground = Brushes.Green;
Dispatcher.Invoke(new Action(() => { currentlyOnlineParagraph.Inlines.Add(r); }), DispatcherPriority.ContextIdle);

I get this error:

InvalidOperationException was unhandled
An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
Additional information: The calling thread cannot access this object because a different thread owns it.

screenshot

How can I address this?

Upvotes: 0

Views: 486

Answers (1)

Emmanuel DURIN
Emmanuel DURIN

Reputation: 4913

From the few lines of code I see,I would try to create all graphical objects on the graphical thread, including the Run object:

Dispatcher.Invoke(new Action(() => {   
   Run r = new Run((string)name + Environment.NewLine);
   r.Foreground = Brushes.Green;
   currentlyOnlineParagraph.Inlines.Add(r);   
}), DispatcherPriority.ContextIdle);

Upvotes: 2

Related Questions