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.

2 Answers 2

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);

    }
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.