Is reusing GDI + objects a bad practice? (or: how to use many nested blocks without a headache?)

I am currently writing a fairly sophisticated drawing method for a user control that includes a fair amount of drawing code. I know that all GDI + resources must be correctly located, so I wrap each of them in a block using.

But when I noticed that I used three blocks usingfor three different ones SolidBrushes, I wondered if I could just reuse them. Create SolidBrush, draw with it, assign a different color, draw something else, etc. And put Dispose()an end to it.

Is such a thing appropriate or am I thinking too much here? I don’t really like too many blocks usingnested in each other. While a good sample, it interferes with readability from time to time.

+3
source share
3 answers

Well, reuse is optimization, and it's probably premature, and therefore: Yes, this is bad practice. I would wait until a clear performance issue appears on the surface, and then find the bottleneck. You would trade some (unknown) performance gains for the rapidly growing complexity of managing the state of these components.

:

 using (var a = ...)
 using (var b = ...)
 using (var c = ...)
 {

 }
+5

I think there is nothing wrong with this practice. But I think you can reuse the created brushes. In my own UserControls, if I use Brushes, I store them in the local variable UserControl and delete them when I delete UserControl.

public class MyUserControl : UserControl{

  private SolidBrush _brush;

  public MyUserControl() {
    _brush = new SolidBrush(Color.Red);
  }

  protected override void OnPaint(PaintEventArgs e){
    // Draw with the brush;
  }

  protected override void Dispose(bool disposing){
    // other Dispose logic
    if (_brush != null) {
      _brush.Dispose();
    }
  }
}
+1
source

Source: https://habr.com/ru/post/1718788/


All Articles