3

I get this exception on that code. How to fix it?

Excepton:

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

Code:

    void CamProc_NewTargetPosition(IntPoint Center, System.Drawing.Bitmap image)
    {
        IntPtr hBitMap = image.GetHbitmap();
        BitmapSource bmaps = Imaging.CreateBitmapSourceFromHBitmap(hBitMap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

        Dispatcher.BeginInvoke((Action)(() =>
        {
            labelX.Content = String.Format("X: {0}", Center.X); //OK Working
            labelY.Content = String.Format("Y: {0}", Center.Y); //OK Working
            pictureBoxMain.Source = bmaps; // THERE IS EXCEPTON
        }), DispatcherPriority.Render, null);

    }

pictureBoxMain is System.Windows.Controls.Image.

Hooch
  • 28,817
  • 29
  • 102
  • 161

2 Answers2

7

You can freeze the BitmapSource so that it can be accessed from any thread:

void CamProc_NewTargetPosition(IntPoint Center, System.Drawing.Bitmap image)
    {
        IntPtr hBitMap = image.GetHbitmap();
        BitmapSource bmaps = Imaging.CreateBitmapSourceFromHBitmap(hBitMap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
        bmaps.Freeze();

        Dispatcher.BeginInvoke((Action)(() =>
        {
            labelX.Content = String.Format("X: {0}", Center.X);
            labelY.Content = String.Format("Y: {0}", Center.Y);
            pictureBoxMain.Source = bmaps;
        }), DispatcherPriority.Render, null);

    }
Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
2

You could Freeze the image, as suggested in another thread, which gets rid of the threading restriction but makes the image immutable.

WPF/BackgroundWorker and BitmapSource problem

Community
  • 1
  • 1
James
  • 5,355
  • 2
  • 18
  • 30