Say I create a Bitmap
Bitmap bitmap = new Bitmap(320, 200);
When I write it to some stream (in my case, it's a HttpResponseStream, as given out by HttpListenerResponse), everything is fine:
bitmap.Save(stream, ImageFormat.Png);
I don't need to bitmap.Dispose(), the resources used by the bitmap will get cleaned up automatically. The problem with directly writing a Png to a non-seekable stream however is that it might result in A generic error occurred in GDI+, which happened to me when I tried my Asp app on Azure. So this is how my code looks now:
using (MemoryStream ms = new MemoryStream())
{
bitmap.Save(ms, ImageFormat.Png);
ms.WriteTo(stream);
}
Now unless I bitmap.Dispose() afterwards, this will leak.
Rephrased question to get more specific answers: Why does this leaking of Bitmap memory seem to depend on what type of stream I save it to?
Update: As I've been asked in comments if I'm sure it's a leak. Calling the above repeatedly in a stress test, my w3wp process will go up to gigs and gigs of memory used until my machine start swapping and it will not clean up.