日期:2014-05-20  浏览次数:20767 次

线程里显示图片流问题
public   delegate   void   MyInvoke(Stream   receiveStream);
private   void   Updatepicturex(Stream   receiveStream)
{
      pictureBox1.Image   =   System.Drawing.Image.FromStream(receiveStream);
}
private   void   TheardFunc()
{
    MyInvoke   mi   =   new   MyInvoke(Updatepicturex);
    this.BeginInvoke(mi,   new   object[]   {   receiveStream   });
}
这样为什么会出错?

------解决方案--------------------
1.Updatepicturex是在主线程之外的另一个线程,你传递的是一个Stream对像,如果你在主线程中关闭或释放了receiveStream ,那么在线程Updatepicturex中将报错,改成下面的方法

private delegate void MyInvoke(byte[] byImage);
参数为byte[],不使用对象

在线程Updatepicturex中再读到对象中
private void Updatepicturex(byte[] byImage)
{
using (MemoryStream ms = new MemoryStream())
{
ms.Write(byImage,0,byImage.Length );
lock(this)
pictureBox1.Image = Image.FromStream(ms);
ms.Close();
ms.Dispose();
}// end ms
}

2.Updatepicturex是另一个线程,所以不能直接使用主线程中的pictureBox1,虽然直接访问并不会出错,但是可能会带来其它一些未知的问题,加锁也不是一个好办法,应该在主线程中更新pictureBox1