How do I prevent memory leak from SolidColorBrush object?

1.7k Views Asked by At

There's no option to dispose SolidColorBrush.

How do I prevent memory leak from SolidColorBrush object?

I can't even use 'using' as SolidColorBrush doesn't implement IDisposable Interface.

2

There are 2 best solutions below

0
On BEST ANSWER

Don't create new SolidColorBrush instances.

Use the predefined brushes in System.Windows.Media.Brushes.

Otherwise, create a single instance, and re-use that.

0
On

Here is my experience.

If I use below code there is a huge memory leak while running it couple hundred thousand times.

SolidColorBrush brush = new SolidColorBrush( helper.ConvertValueToColorCanvas(colorValue, slider.Value));
mainCanvas.rects.Add(new MyCanvas.MyRect() { Brush = brush, Rect = new Rect(p0X + leftMargin + width, p0Y + height, (p2X - p0X), (p2Y - p0Y)) });

But if I use below code, the leak become partially stop.

mainCanvas.rects.Add(new MyCanvas.MyRect() { Brush = new SolidColorBrush( helper.ConvertValueToColorCanvas(colorValue, slider.Value)), Rect = new Rect(p0X + leftMargin + width, p0Y + height, (p2X - p0X), (p2Y - p0Y)) });

So instead of creating new solidbrush variable, if you use it just directly in constructor, it worked for me.