System.Drawing objects unmanaged resource disposing

偶尔善良 提交于 2019-12-12 23:15:52

问题


I have the following code:

using System.Drawing;
...
Graphics _graphics = Graphics.FromImage(...)
...
public void Draw(Stream stream, Rectangle rect, Color color) {
    _graphics.FillRectangle(new SolidBrush(Color), 0, 0, Width, Height);
    _graphics.DrawImage(new Bitmap(stream), rect);
}

Should I surround the drawImage with using on new Bitmap(...)? Same question on the new SolidBrush(...)


回答1:


Yes, you should wrap them in using statements. Also you should ensure that the Dispose methods is invoked on the _graphics instance that you are using in this class. This could be done by having the containing class implement IDisposable so that the consumer of this class could wrap it in a using statement.




回答2:


Yes, disposing these resources is important. Particularly a bitmap is troublesome, it consumes lots of unmanaged memory to store the pixel data but the managed Bitmap class wrapper is very small. You can create a lot of Bitmap objects before triggering a garbage collection, giving high odds that the Bitmap constructor will start failing because there is no more unmanaged memory left.

So rewrite it like this:

public void Draw(Stream stream, Rectangle rect, Color color) {
    using (var bmp = new Bitmap(stream))
    using (var brush = new SolidBrush(Color)) {
        _graphics.FillRectangle(brush, 0, 0, Width, Height);
        _graphics.DrawImage(bmp, rect);
    }
}


来源:https://stackoverflow.com/questions/14029451/system-drawing-objects-unmanaged-resource-disposing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!