使用WPF图像进行线程处理(System.InvalidOperationException) [英] Threading with WPF Images (System.InvalidOperationException)

查看:50
本文介绍了使用WPF图像进行线程处理(System.InvalidOperationException)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用线程从网站获取图像并将其拍摄回父表单(WPF)进行显示.我遇到了一个问题,并设法将其调试为以下示例:

I'm using a thread to get an image from a website and shoot it back to the parent form (WPF) to display. I ran into an issue and have managed to debug it to this example:

public void Watch()
{
  while (true)
  {
    Bitmap bmp = new Bitmap(1, 1);
    BitmapImage bmpImg = new BitmapImage();

    this.SetImage(bmp, bmpImg);
  }
}

public delegate void SetImageCallback(Bitmap bmp, BitmapImage bmpImg);

private void SetImage(Bitmap bmp, BitmapImage bmpImg)
{
  if (!this.imgVideo.Dispatcher.CheckAccess())
  {
    SetImageCallback del = new SetImageCallback(SetImage);
    this.Dispatcher.Invoke(del, bmp, bmpImg);
  }
  else
  {
    Bitmap bitmap = bmp;
    BitmapImage bitmapImage = bmpImg;
  }
}

请记住,Watch()在其自己的线程上运行.如果我使用位图对象(可以在Window Forms中与PictureBox一起使用),则一切正常.也就是说,当我到达

Keep in mind that Watch() runs on its own thread. If I use the bitmap object (which I can use with PictureBox in Window Forms) everything works great. That is, debugging this code, when I get to the line

Bitmap bitmap = bmp;

并检查变量bmp,一切都很好,并按预期工作.但是,当我到达下一行时

And inspect the variable bmp, everything is great and works as expected. HOWEVER, when I get to the next line

BitmapImage bitmapImage = bmpImg;

然后检查变量bmpImage,我得到了大量的System.InvalidOperationException.实际上,当将其分配给WPF Image对象时,它说:调用线程无法访问此对象,因为另一个线程拥有它."为什么我会遇到WPF BitmapImages(设置ImageSource所需)而不是Windows Forms Bitmap对象(可用于设置PictureBox)的问题?如何在WPF中解决此问题?

And inpsect the variable bmpImage, I get a ton of System.InvalidOperationException's. When this is in practice and gets assigned to a WPF Image object, it says that "The calling thread cannot access this object because a different thread owns it." Why am I running into this issue with WPF BitmapImages (which are required to set an ImageSource) but NOT in Windows Forms Bitmap objects (which can be used to set a PictureBox)? How do I fix this in WPF?

推荐答案

WPF中的大多数对象属于此类:它们不能在不同线程之间共享.但是,某些低级资源(例如画笔和位图)是从称为Freezable的特殊类派生的,如果冻结了 ,则可以在不同线程之间共享.当然,一旦冻结了对象,就不能再以任何方式对其进行修改.要冻结可冻结对象,只需调用Freeze,这将防止跨线程异常.

Most objects in WPF are of this category: they cannot be shared between different threads. However certain low-level resources such as brushes and bitmaps are derived from a special class called Freezable that if frozen can be shared between different threads. Of course once an object is frozen is can no longer be modified in any way. To freeze a freezable object simply call Freeze and this will prevent cross-thread exceptions.

这篇关于使用WPF图像进行线程处理(System.InvalidOperationException)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆