Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a WPF window in the main thread. On button clock of this window i am loading the data. Meanwhile i am using a seperate thread to display a wait screen. But i am not able to set the main window as the parent of the wait screen. It throws following error: The calling thread cannot access this object because a different thread owns it

like image 238
user907631 Avatar asked Aug 24 '11 10:08

user907631


2 Answers

You want to look into the Dispatcher.Invoke method.

like image 182
Daren Thomas Avatar answered Oct 22 '22 02:10

Daren Thomas


You could use the BackgroundWorker class to perform your asynchronous operations; it should take care of any thread affinity issues you might be having. It's as simple to use as wiring up a couple of events.

This should get you started.

Alternatively you can use Dispatcher.Invoke to perform the operation on the correct thread:

private void DoStuffOnThread()
{
    Dispatcher.Invoke(new Action(DoStuffOnUIThread));
}

private void DoStuffOnUIThread()
{
    // ...
}
like image 20
Phil Gan Avatar answered Oct 22 '22 01:10

Phil Gan