【发布时间】:2015-08-23 15:41:26
【问题描述】:
我想使用尽可能少的 RAM - 使用 Windows 窗体和 Aforge.Net 来捕获视频。 问题是,当我尝试例如“.Dispose()”某些元素时出现异常:
static void Main()
{
Console.WriteLine("Main");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1()); <----- here VS showing me an exception (An unhandled exception of type 'System.InvalidOperationException' occurred in System.Drawing.dll)
}
执行此操作的代码:
public void setLocalCamera(string cameraName)
{
videoSource = new VideoCaptureDevice(cameraName);
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
videoSource.Start();
}
Bitmap bitmap;
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
if (bitmap != null)
bitmap.Dispose(); <--- here is the problematic code
bitmap = (Bitmap)eventArgs.Frame.Clone();
pB_Camera.Image = bitmap;
}
此代码会导致随机时间异常(我不知道究竟是什么触发了它)。我还尝试了一些我发现但没有任何工作/帮助的其他解决方案(比如在 pB_Camera.Image = bitmap; 之后 make bitmap.Dispose(); 但这也是一个例外)
如何解决此问题并尽可能多地释放 RAM?
【问题讨论】:
-
您必须处理您不再需要的 old 位图。不是你要展示的那个。所以只需使用 if (pB_Camera.Image != null) pB_Camera.Image.Dispose();
-
当我尝试您的代码时,我在同一个地方遇到了异常:System.Drawing.dll 中发生了“System.InvalidOperationException”类型的未处理异常附加信息:对象当前正在其他地方使用。
-
您可以先将
pB_Camera.Image设置为NULL,然后处理位图并重新分配给pB_Camera。 -
我在开头添加了这样的内容: pB_Camera.Image = null;if (bitmap != null) bitmap.Dispose();我没有看到任何错误,RAM 使用量约为 100 mb(OK)。但是有个小问题。每隔几秒钟我注意到位图上闪烁的白色图像(不是来自相机的图像)。