错误:对象当前正在其他地方使用。

时间:2011-01-28 01:47:11

标签: c# camera picturebox

我开发了一个来自DSLR相机的连续读取图像流的应用程序。

while (!liveViewExit)
        {
            // Create a Memory Stream 
            stream = new IntPtr();

            // Get the bitmap image from the DSLR
            bmp = GetEvfImage(stream);


            if (bmp != null)
            {

                // Crop the image.
                picImage = (System.Drawing.Image)bmp.Clone(new Rectangle(10, 0, 492, 768), bmp.PixelFormat);
                try
                {
                    if (picImage != null)
                        this.picLiveView.Image = (System.Drawing.Image)picImage.Clone();
                }
                catch (Exception ex)
                {
                    Utility.HandleError(ex);
                }


            }
        }

运行一段时间后,我对这行代码有这个错误:

   this.picLiveView.Image = (System.Drawing.Image)picImage.Clone();


Object is currently in use elsewhere.(   at System.Drawing.Image.get_FrameDimensionsList()
   at System.Drawing.ImageAnimator.CanAnimate(Image image)
   at System.Drawing.ImageAnimator.ImageInfo..ctor(Image image)
   at System.Drawing.ImageAnimator.Animate(Image image, EventHandler onFrameChangedHandler)
   at System.Windows.Forms.PictureBox.Animate(Boolean animate)
   at System.Windows.Forms.PictureBox.Animate()
   at System.Windows.Forms.PictureBox.InstallNewImage(Image value, ImageInstallationType installationType)
   at System.Windows.Forms.PictureBox.set_Image(Image value)

我认为picLiveView PictureBox控件尚未准备好接受新图像。 知道如何检测PictureBox是否仍在使用中。

//已添加:

这是一个单一的主题。我认为图片框不够快,无法在while循环中处理图片对象。

2 个答案:

答案 0 :(得分:2)

多个线程是否正在更新picLiveView图片?如果是这样就可以解释这个问题。只需使用一个线程,并序列化更新 - 或者您也可以使用锁来访问picLiveView

private readonly object myLock = new object();
...


if (picImage != null)
{
   lock(myLock)
   {
      this.picLiveView.Image = (System.Drawing.Image)picImage.Clone();
   }
} 

答案 1 :(得分:0)

我知道已经很晚了......但试试这个,如果有人有同样的问题......

if (bmp != null)
            {

                // Crop the image.
                picImage = (System.Drawing.Image)bmp.Clone(new Rectangle(10, 0, 492, 768), bmp.PixelFormat);

    **Bitmap img = new Bitmap(picImage);
    picImage.Dispose();
    picImage = null;**

      try
                {
                    if (picImage != null)
                        **this.picLiveView.Image = img;**
                }
                catch (Exception ex)
                {
                    Utility.HandleError(ex);
                }


            }