taminov
taminov

Reputation: 591

System.Drawing objects unmanaged resource disposing

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(...)

Upvotes: 1

Views: 1119

Answers (2)

Hans Passant
Hans Passant

Reputation: 941317

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);
    }
}

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

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.

Upvotes: 4

Related Questions