我想写一个从服务器接收一些JPEG帧程序(远程桌面 - 等),将它们转换成位图图像,然后将它们显示在Windows窗体上。我试图让例程尽可能轻,但也许我做错了,因为我总是收到一个System.OutOfMemoryException。我的代码如下:我得到System.OutOfMemoryException。有一种方法可以让我的代码更轻松?
编辑:补充说,与此有关的异常
private void WatcherRoutine()
{
Boolean lLoopEnd = false;
Bitmap lCurrent = null;
//Graphics lGraphics = null;
Image lImg = null;
BinaryReader lBRVideo = new BinaryReader(this._state.Video.GetStream());
while (lLoopEnd == false)
{
try
{
// Reads frame type
switch (lBRVideo.ReadByte())
{
// Frame received is a big frame (ie a desktop screenshot)
case Constants.BIGFRAME:
{
// Reads frame size in bytes
Int32 lVideoLength = lBRVideo.ReadInt32();
if (lVideoLength > 0)
{
// Stores frame in a stream
MemoryStream ms = new MemoryStream(lBRVideo.ReadBytes(lVideoLength));
// Creates image from stream
lImg = Image.FromStream(ms);
ms.Dispose();
// Creates bitmap from image
lCurrent = new Bitmap(lImg);
lImg.Dispose();
// Passes image to windows form to display it
this.Invoke(this._state.dUpdateVideo, lCurrent);
////lGraphics = Graphics.FromImage(lImg);
//lGraphics.Dispose();
}
}
break;
// Diff frame (ie a small part of desktop that has changed)
// Commenting this part makes the exception disappear :|
case Constants.DIFFFRAME:
{
Int16 lX = lBRVideo.ReadInt16(),
lY = lBRVideo.ReadInt16();
Int32 lVideoLength = lBRVideo.ReadInt32();
if (lVideoLength > 0)
{
//Byte[] lVideoImg = lBRVideo.ReadBytes(lVideoLength);
//Image lImgDiff = Image.FromStream(new MemoryStream(lVideoImg));
////if(lGraphics != null)
//{
// lGraphics.DrawImage(lImgDiff, lX, lY);
// this.Invoke(this._state.dUpdateVideo, new Bitmap(lImg));
//}
}
}
break;
case Constants.CURSOR:
{
Int16 lX = lBRVideo.ReadInt16(),
lY = lBRVideo.ReadInt16();
// TODO
}
break;
default:
break;
}
}
catch (Exception e)
{
if (this._state.WorkEnd == false)
{
this._state.WorkEnd = true;
this.BeginInvoke(this._state.dDisconnect);
}
lLoopEnd = true;
SmartDebug.DWL(e.Message);
}
}
}
dUpdateVideo一部分包含这个小程序的委托。也许我已释放pBmp?
private void UpdateVideo(Bitmap pBmp)
{
this.VideoPictureBox.Image = pBmp;
}
看不到如果释放由lCurrent – imaximchuk
豌豆用于提供dUpdateVideo的源存储器,它也可以是内存泄漏的来源。 查看是否收到了在lVideoLength(也可能是非常大的数字,由于一些错误) – imaximchuk
我觉得这是你的二进制协议和视频长度的问题以某种方式搞砸了(见lBRVideo.ReadInt16和ReadInt32叫你注释掉正确的数据) – imaximchuk