Out Of Memory exception / Cleanup unmanaged memory

183 Views Asked by At

I'm trying to record a video from a certain window of an application (the window is showing some graphics build with DirectX) anyway

What I'm actually doing is, taking snapshots from that window and passing it to the AVIWriter from Aforge.net, I'm repeating the process 20 time per-second to get a video with 20fps.

Everything is working fine for 30 to 40 seconds, anything longer I get an out of memory exception. Upon profiling with JetBrains dotMemory, I found that the unmanaged memory is increasing rapidly. Although the call to Dispose() is made to remove allocations. Still memory consumption is high. I tried also using

GC.Collect();
GC.WaitForPendingFinalizers();

but without success here my code below, it's running in a Backgroundworker which repeat every 50 ms until the button for CancellationPending is hit.

DisplayMode dm = device.DisplayMode;
Bitmap bmp = null;
Surface renderTarget = device.GetRenderTarget(0);
Surface destTarget = device.CreateOffscreenPlainSurface(ClientRectangle.Width, ClientRectangle.Height, dm.Format, Pool.SystemMemory);
device.GetRenderTargetData(renderTarget, destTarget);
GraphicsStream gs = SurfaceLoader.SaveToStream(ImageFileFormat.Bmp, destTarget);
renderTarget.Dispose();
destTarget.Dispose();
bmp = new Bitmap(gs);
gs.Dispose();
image = new Bitmap(bmp, size);
bmp.Dispose();
writer.AddFrame(image);
image.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
0

There are 0 best solutions below