6
votes

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

3

3 Answers

7
votes

You want to look into the Dispatcher.Invoke method.

5
votes

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()
{
    // ...
}
0
votes

The problem you are running into is that windows/controls have thread affinity (they are "owned" by a particular thread), and you cannot mix them between threads.

If you want the wait screen's parent to be the main window, you should create the wait screen on the main window's thread. Then, on the other thread, you can tell the wait screen to display by using Invoke.

There is a good article on cross-thread operations in WPF here (search down for Figure 4 Updating the UI):

http://msdn.microsoft.com/en-us/magazine/cc163328.aspx