Search code examples
c#memory-leaksgdi

C# BufferedGraphics Memory Leak


My code has the following form:

while (Globals.Running)
{
    if ((Form.Visible == false) || (Form.ContainsFocus == false) || (Form.Enabled == false))
    {
        Threading.Thread.Sleep(100);
    }
    else
    {
        Update();
        Draw();
    }

    Application.DoEvents();
}

When I look at the process in the Task Manager, I see the memory consumed increases by 8K each second.

If I comment out the Draw() call, memory is stable. Therefore, memory is leaking inside Draw. Here is how that method looks like:

private static void Draw()
{
    BufferedGraphics.Graphics.Clear(Color.CornflowerBlue);
    //Engine.Draw(BufferedGraphics.Graphics);
    BufferedGraphics.Render();
    ++FPS;
}

So, even without me drawing anything, memory is lost. If I comment out .Clear line, it still leaks. If I comment out .Render line, it still leaks. If I comment out both of those, it stops leaking.

BufferedGraphics is initialized in the constructor like this:

BufferedGraphics = BufferedGraphicsContext.Allocate(Graphics.FromHwnd(Form.Handle), Form.ClientRectangle);

So, my question is, why is rendering nothing/clearing the graphics context leaking memory? Or is there something else at play here?


Solution

  • Don't use application.doEvents! Use a dispatcher to update the UI whilst operating on a different thread, it wil prevent blocking of the UI and changes won't leak memory

    Example: Dispatcher.Invoke to update UI Control