Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is better approach to dispose Brush in User Control

Tags:

c#

.net

winforms

Is it better approach to use a new Brush in Paint event i.e

protected override void OnPaint(PaintEventArgs e) {
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    using (SolidBrush b = new SolidBrush(Color.FromArgb(129, 242, 121))) {
        for (int i = 0; i < 12; i++) {    
            e.Graphics.FillPath(b, path[i]);
        }
    }
    base.OnPaint(e);
}

or define once at top and dispose in Dispose Method i.e

SolidBrush _brush;
protected SolidBrush Brush {
    get {
        if (_brush == null)
            _brush = new SolidBrush(Color.FromArgb(129, 242, 121));
        return _brush;
    }
}
like image 973
Nasir Mahmood Avatar asked Nov 24 '11 07:11

Nasir Mahmood


1 Answers

Creating and destroying drawing objects like pens and brushes is very cheap, takes about a microsecond. A very small fraction of the cost of the code that actually does the drawing, typically measured in milliseconds. You should therefore avoid storing them, that just takes up precious space in the operating system GDI object heap, a resource that needs to be shared by all running processes. The only drawing object that's expensive to create is a font. However, Winforms solves this by caching fonts internally.

Make it consistent, always apply the using statement to drawing objects you create.

like image 105
Hans Passant Avatar answered Nov 15 '22 16:11

Hans Passant