WPF - 如何从另一个线程更新 "System.Windows.Controls.Image"?

3

我在这段代码中遇到了一个异常。

如何修复它?

异常信息:

由于不同的线程拥有该对象,调用线程无法访问此对象。

代码:

    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是System.Windows.Controls.Image。

2个回答

7
你可以冻结BitmapSource,以便从任何线程访问:
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);

    }

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接