简体   繁体   中英

What is better approach to dispose Brush in User Control

Is it better approach to use a new Brush in Paint event ie

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 ie

SolidBrush _brush;
protected SolidBrush Brush {
    get {
        if (_brush == null)
            _brush = new SolidBrush(Color.FromArgb(129, 242, 121));
        return _brush;
    }
}

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.

Use predefined Brushes if you can (and do not dispose them). If you can't I suggest do not create your brushes on every paint but cache them:

IDictionary<Color, Brush> SolidBrushes; //... cache
Brush GetSolidBrush(Color color) {
    if(color.IsSystemColor) 
        return GetSystemBrush(color);
    Brush result = null;
    if(!SolidBrushes.TryGetValue(color, out result)) {
        result = new SolidBrush(color);
        SolidBrushes.Add(color, result);
    }
    return result;
}
Brush GetSystemBrush(Color color) {
    return SystemBrushes.FromSystemColor(color);
}

ADDITION: The best answer on this question may be "depends on task". The brush creation is expensive, because of the brushes themselves (it is managed wrapper on unmanaged GDI+ object), and also because of the garbage collection with all those brushes on every Paint event. So if you use multiple brushes it is better to cache them (of course the cached brushes should be disposed on disposing of owner control or on skin changing). But if you use only one brush (the first case) thr cache is not needed - only use the brush in using block

从性能的角度来看,我更喜欢创建一个画笔并将其配置在Dispose方法中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM