I have a draw function which draws lines that are gradient from one end to the other. I'm only drawing about forty or so lines each time. Each time, I generate a new set of Linear gradient brushes. The old set is a local variable with no ties to any object. My program only uses about 26 MB of memory. It'll work fine for several minutes before randomly throwing an out of memory exception when allocating a new linear gradient brush. As you can see, memory was at 25.7 MB when the exception occurred.
Minimal Example Code (will throw the memory exception):
Note: The following code only triggers the exception if it is used in a redraw for the graphics context, that context is resized, and even then, only after several minutes.
class DrawImpl
{
private static Pen routePen = new Pen(Color.Black);
public static void Draw(Graphics g, Point[] ps)
{
g.SmoothingMode = SmoothingMode.HighQuality;
if (ps != null && ps.Length > 0)
{
for (int i = 0; i < ps.Length; ++i)
{
int prevI = (((i - 1) % ps.Length) + ps.Length) % ps.Length;
using (LinearGradientBrush routeBrush = new LinearGradientBrush(ps[prevI], ps[i], Color.Red, Color.Blue))
{
routePen.Brush = routeBrush;
g.DrawLine(routePen, ps[prevI], ps[i]);
}
}
GC.Collect();
}
}
}