For some of my winforms applications I need to create a whole bunch of GDI+ objects (brushes, pens, fonts, etc) and use them over and over again. I created a ghetto caching singleton to accomplish what I need, but the code smell is overwhelming...
public sealed class GraphicsPalette
{
public static readonly GraphicsPalette Instance = new GraphicsPalette();
static GraphicsPalette()
{
}
private Dictionary<Color, Brush> solidBrushes;
//multithreading
private object brushLock;
private GraphicsPalette()
{
solidBrushes = new Dictionary<Color, Brush>();
brushLock = new object();
}
public Brush GetSolidBrush(Color color, int alpha)
{
return GetSolidBrush(Color.FromArgb(alpha, color));
}
public Brush GetSolidBrush(Color color)
{
if (!solidBrushes.ContainsKey(color))
{
lock (brushLock)
{
if (!solidBrushes.ContainsKey(color))
{
Brush brush = new SolidBrush(color);
solidBrushes.Add(color, brush);
return brush;
}
}
}
return solidBrushes[color];
}
}
- Is there a better way for me to reuse these GDI+ objects, as opposed to instantiating them all over again every time
OnPaint()
etc gets called? - Will the GDI+ objects cause an unmanaged memory leak once the program terminates, or will the finalizer for each
Brush
object get called which will in turn release any unmanaged resources?
I apologize if this is a repeat, but I didn't find any similar questions.
Dispose(bool)
method that is called from theDispose()
method passingfalse
as a parameter, and from the finalizer, passingtrue
as a parameter. So I think you're safe regarding the memory leak. But I would take extra caution with creating too many temporary resources as it might cause a memory stress (they would get disposed sometime, but there is no guarantee the GC will get to them on time...)