5YrsLaterDBA
5YrsLaterDBA

Reputation: 34760

C# WPF project, how to avoid InvalidOperationException?

We have a WPF project. I got the following error:

InvalidOperationException was unhandled
The calling thread cannot access this object because a different thread owns it.

I try to get value from a TextBox from a worker thread created by me.

How to avoid this. I was able to avoid this in another Form project by using delegate call back and Invoked() method but somehow it doesn't work in this WPF project.

any simple sample code? thanks,

Upvotes: 2

Views: 3088

Answers (2)

Gareth
Gareth

Reputation: 2791

How about something along the lines of:

        if (!Dispatcher.CheckAccess()) 
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Normal,
            (MyDelegate)delegate
            {
                // Get value
            });
        } 
        else 
        { 
            // Get value
        }

Upvotes: 4

Reed Copsey
Reed Copsey

Reputation: 564403

You need to use the Dispatcher to handle this. Instead of using Control.Invoke like in Windows Forms, you now need to use Dispatcher.Invoke or Dispatcher.BeginInvoke to marshal your call back onto the UI thread.

Upvotes: 5

Related Questions