The calling thread cannot access this object because a different thread owns it

If you see this error message you are probably playing around with C# multithreading (WPF may be?) and doing something wrong. But don't worry it shouldn't be that hard to solve this problem.

I encountered the same problem in a WPF project that I have been developing for fun.

The problem was this: I had a long running method and I had created a new thread in the thread pool using “Task.Factory.StartNew” to run that method in this new thread. The aim of using a seperate thread was to keep the UI responsive while performing the time-taking task in a thread other than UI thread. But one of the methods that ran in this new thread was trying to access and update a control in the UI. That is exactly where the exception was thrown.

In WPF, only the thread that created a Dispatcher Object may access UI elements. A background thread that is spun off from the main UI thread cannot update the contents of an element that was created on the UI thread.

In order for the background thread to access the properties of UI elements, the background thread must delegate the work to the Dispatcher associated with the UI thread. This is accomplished by using either Invoke (synchronous) or BeginInvoke (asynchronous).

In the method that runs in the new thread (background thread) you need to call Dispatcher.BeginInvoke (or Invoke) to perform the UI element update as a dispatcher “action”:

Dispatcher.BeginInvoke(new Action(() => "do things here or call a method to update the variables created on the main ui thread"));

This way you can get rid of this error message and everthing will work just fine.

Hope this helps someone.

Good luck,
Serdar.

Leave a Reply

Your email address will not be published. Required fields are marked *