WPF Dispatcher {"The calling thread cannot access this object because a different thread owns it."}

Orri picture Orri · Jun 6, 2010 · Viewed 22.8k times · Source

first I need to say that I´m noob with WPF and C#. Application: Create Mandelbrot Image (GUI) My dispatcher works perfectly this this case:

  private void progressBarRefresh(){

       while ((con.Progress) < 99)
       {
           progressBar1.Dispatcher.Invoke(DispatcherPriority.Send, new Action(delegate
                {
                    progressBar1.Value = con.Progress;
                }
              ));
       }
  }

I get the Message (Title) when tring to do this with the below code:

bmp = BitmapSource.Create(width, height, 96, 96, pf, null, rawImage, stride);

this.Dispatcher.Invoke(DispatcherPriority.Send, new Action(delegate
            {                     
                img.Source = bmp;
                ViewBox.Child = img;  //vllt am schluss
            }
          ));

I will try to explain how my program works. I created a new Thread (because GUI dont response) for the calculation of the pixels and the colors. In this Thread(Method) I´m using the Dispatcher to Refresh my Image in the ViewBox after the calculations are ready.

When I don't put the calculation in a separate Thread then I can refresh or build my Image.

Answer

Irfan picture Irfan · Dec 5, 2012

Just in case you want the object to be shared among different threads then always create that object on UI thread. Later when you want to access the object, you can check if you have access to object. If you dont have access, re-invoke the function with UI thread access. example code below:

    private void YourMethod()
    {
        if (Application.Current.Dispatcher.CheckAccess())
        {
            // do whatever you want to do with shared object.
        }
        else
        {
            //Other wise re-invoke the method with UI thread access
            Application.Current.Dispatcher.Invoke(new System.Action(() => YourMethod()));
        }
    }