Why is there a memory leak when I do not .Dispose() Bitmaps that I .Save() to a MemoryStream?

后端 未结 3 1742
灰色年华
灰色年华 2021-01-06 13:39

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 give

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-06 14:07

    You must dispose the bitmap in order to release the GDI+ resources. It is that simple. It is one of the few times calling Dispose is required. If you are caching your bitmap to reduce disk access then clone the image and use the clone to save to the stream. I strongly recommend flushing, closing, and disposing of stream. When done, set clone and stream variables to null.

提交回复
热议问题