When I make screenshots in my XNA game, each texture.SaveAsPng consumes some memory and it doesn’t seem to return back to the game. So eventually I run out of memory. I tried saving the texture data into FileStream and MemoryStream, hoping I could save it from there as Bitmap, but the results are the same. Is there a way to forcefully free this memory or some workaround that will let me get image data and save it some other way without running into out of memory exception?
sw = GraphicsDevice.Viewport.Width;
sh = GraphicsDevice.Viewport.Height;
int[] backBuffer = new int[sw * sh];
GraphicsDevice.GetBackBufferData(backBuffer);
using(Texture2D texture = new Texture2D(GraphicsDevice, sw, sh, false,
GraphicsDevice.PresentationParameters.BackBufferFormat))
{
texture.SetData(backBuffer);
using(var fs = new FileStream("screenshot.png", FileMode.Create))
texture.SaveAsPng(fs, sw, sh); // ← this line causes memory leak
}
You might be able to create the Bitmap from the texture bytes directly and bypass the internal method to check if the
SaveAsPngis leaking or its something else.Try This extension method (unfortunatly I cannot test (no xna at work) but it should work.)
Its a bit crude but you can clean it up (if it even works).
An last but not least (if all other attempts fail) you could call
GarbageCollectionyourself but this is NOT recommended as its pretty bad practice.The above code should be LAST resort only.
Good luck.