【问题标题】:WPF - Update "System.Windows.Controls.Image" from another threadWPF - 从另一个线程更新“System.Windows.Controls.Image”
【发布时间】:2011-09-28 08:35:43
【问题描述】:

我在该代码上遇到此异常。 如何解决?

例外:

调用线程不能访问这个 对象,因为不同的线程拥有 它。

代码:

    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。

【问题讨论】:

    标签: c# .net wpf multithreading wpf-controls


    【解决方案1】:

    您可以冻结 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】:

      您可以按照另一个线程中的建议冻结图像,从而摆脱线程限制但使图像不可变。

      WPF/BackgroundWorker and BitmapSource problem

      【讨论】:

        猜你喜欢
        • 2020-10-15
        • 2011-08-12
        • 1970-01-01
        • 2017-01-04
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        相关资源
        最近更新 更多