问题
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.
回答1:
Don't create new SolidColorBrush
instances.
Use the predefined brushes in System.Windows.Media.Brushes
.
Otherwise, create a single instance, and re-use that.
回答2:
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.
来源:https://stackoverflow.com/questions/40904567/how-do-i-prevent-memory-leak-from-solidcolorbrush-object