0

I've got everything working except for this call which throws an error no matter how I change things.

This is a WPF Application written in C#.

Things I've Tried:

  • Accessing it from a Static Context
  • Accessing it from the UI Thread (mainWindow.img)

Here is my current code where I access it in a static context:

        var worker = new Thread(() => RenderBarcodeImage(imageBytes));
        worker.SetApartmentState(ApartmentState.STA);
        worker.Name = "RenderBarcodeImage";
        worker.IsBackground = true;
        worker.Start();
        worker.Join();
        Application.Current.Dispatcher.Invoke(new Action(() =>
        {
            var mainWindow = Application.Current.MainWindow as MainWindow;
            if (mainWindow == null) return;
            mainWindow.PairingBarcodeImage.Stretch = mainWindow.PairingBarcodeImage.Width < MainWindow.img.Width ? Stretch.Uniform : Stretch.None;

            mainWindow.PairingBarcodeImage.Source = MainWindow.img.Source;
            if (mainWindow.PairingBarcodeImage.Source != null)
                mainWindow.SaveBarcodeButton.IsEnabled = true;
        }));

No matter what every time I try to access img it throws

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

How would I access the img object from another thread?

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
nulltron
  • 637
  • 1
  • 9
  • 25
  • 1
    What's the point of spawning an expensive thread if you are going to just sit there and wait for it to complete? Throw that code away and use **async/await** –  Jun 29 '17 at 00:21
  • 1
    Also, not sure why your UI thread code is bothering with **Dispatcher.Invoke** - the current tread **is** the UI thread –  Jun 29 '17 at 00:23
  • See marked duplicate for detailed advice on dealing with cross-thread issues in WPF. If you believe that you have done adequate research (something your question shows no evidence of) and are still unable to solve the problem, post a new question that includes a good [mcve] that reliably reproduces your problem, along with a detailed explanation of what you've done to try to solve the problem and what _specifically_ you are having trouble with. – Peter Duniho Jun 29 '17 at 00:26

0 Answers0