c# - WPF - 从另一个线程更新 "System.Windows.Controls.Image"

标签 c# .net wpf multithreading wpf-controls

我在那个代码上得到了这个异常。 如何解决?

异常:

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

代码:

    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。

最佳答案

您可以卡住 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);

    }

关于c# - WPF - 从另一个线程更新 "System.Windows.Controls.Image",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4686433/

相关文章:

c# - 从字符串数组中删除重复字母的字符串

c# - 我如何在 ASP.NET MVC 中进行分页?

.net - .net core 1.1 中嵌入的 power bi

c# - 接口(interface)可以包含变量吗?

c# - 如何在 Window 启动 C# 时将 wpf 应用程序移动到最小化托盘?

c# - MVC 模型评估为无效,因为缺少一些已发布的数据

c# - 输入字符串包含非 ASCII 或空字符

.net - 错误 : Could not load the file or assembly 'ExcelAddIn1.XmlSerializers' or one of it's dependencies. 系统找不到指定的文件

wpf - 垂直 Epander 会喜欢垂直标题

wpf - 不使用密码框隐藏 TextBox 控件的文本