Memoryleak when saving a bitmap?

I save a screenshot of the current image on the computer:

Rectangle bounds = Screen.GetBounds(Point.Empty); using (var bitmap = new Bitmap(bounds.Width, bounds.Height)) { using (Graphics g = Graphics.FromImage(bitmap)) { g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size); } using (var mss = new MemoryStream()) { bitmap.Save(mss,ImageFormat.Gif); } } 

And this memory symbol is in this code:

 bitmap.Save(mss,ImageFormat.Gif); 

Shouldn't using using everything I use?

Why am I still getting a very high memory when shooting a large number of photos and the memory is not coming back?

Thanks!

+4
source share
2 answers

You can try using BufferManager, it will manage Byte [] for you.

  // declare the BufferManager somewhere. Check thread safety! BufferManager bm = BufferManager.CreateBufferManager(qqq, yyy); // wrap your current code to use the buffer manager Rectangle bounds = Screen.GetBounds(Point.Empty); using (var bitmap = new Bitmap(bounds.Width, bounds.Height)) { using (Graphics g = Graphics.FromImage(bitmap)) { g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size); } byte[] buffer = bm.TakeBuffer(yyy); try { using (MemoryStream stream = new MemoryStream(buffer)) { bitmap.Save(mss,ImageFormat.Gif); } } finally { bm.ReturnBuffer(buffer); } } 
+2
source

You may have encountered the same problem that I encountered when I asked this question on SO.

In my case, the problem was that the MemoryStream did not release its internal byte[] even when Dispose called on it. byte[] not freed until the MemoryStream goes out of scope and is collected by the GC.

This blog post details the cause of the problem and also provides a working solution. This worked for me, and I suspect you are facing the same problem. Essentially, it wraps the underlying MemoryStream in a type that implements the same interface, but sets the thread reference to null when Dispose() called. Since no other objects should have a live link to the internal thread, this allows the GC to attack and clear it.

In addition, this problem is compounded by the fact that the internal byte[] is likely to be allocated to a bunch of large objects, resulting in fragmentation after several distributions.

+3
source

All Articles