How do I prevent memory leak from SolidColorBrush object?

瘦欲@ 提交于 2019-12-11 05:53:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!