locked
Memory leak? RRS feed

  • Question

  • User-1321299942 posted

    I have made a function creating a simple graph.

     

    1    public static System.Drawing.Bitmap Graph(int[] values, int width, int height)
    2 {
    3 Bitmap bitmap = new Bitmap(width, height);
    4 Graphics graphics = Graphics.FromImage(bitmap);
    5 6 // create graph here 7 8 graphics.Dispose();
    9 10 return bitmap;
    11 }
     

     

    Every time I reload the page so that the image containing the graph is recreated, the w3wp.exe (IIS Worker Process) in the Task Manager adds a couple of more megabytes that it uses.

    I have never really thought of performance before when I've made web apps but this is could be a problem.

    I suspect it's the bitmap object that I'm not doing a .Dispose() on that is causing it but what can I do about it?? Obiously I can't .Dispose() before I return it and if I put .Dispose() after that won't run because it exits at return, right?

    Tuesday, June 24, 2008 1:56 PM

All replies

  • User2032526919 posted

    Hi,

    calling Dispose() does not necessarily free the memory immediately (as its done by the garbage collector based on heuristic algorithm). In code like this, consumer of Bitmap object (caller of the method) is responsible for freeing it, this method cannot do it.

    There are patterns to solve it for example with a delegate (disposing with callback approach) something like is done with datareaders in: http://aspalliance.com/526 but it makes using the method more complicated. Or encapsulating this functionality into an instantiable class which deals with disposing (for example implements finalizer etc) and other related tasks however that's obviously a design decision which needs more weight e.g is there clear reasoning for it (task for the class).

    Tuesday, June 24, 2008 2:28 PM
  • User-1321299942 posted

    Not sure if I understood, is it supposed to be done automatically by garbage collector?

    My computer has been running for about 1,5 hour now since restart and w3wp.exe used 24MB when I started and now it's using 85MB, steadily increasing while work on the website and reloading the image.

    Tuesday, June 24, 2008 2:56 PM
  • User2032526919 posted

    In the end you don't free the memory, GC does. Certainly you need to call Dispose if object is disposable (and GDI does use unmanaged resources at some point), but it does not necessarily free the memory immediately .

    See: http://msdn.microsoft.com/en-us/library/0xy59wtx.aspx

    Although for rare cases you can call GC.Collect (http://msdn.microsoft.com/en-us/library/bb384155.aspx

    In your code, caller of the method needs also call Dispose for the Bitmap object after use. Check that part before trying to run forced collection. Note also that memory cleanup is also impacted by do you run your application in debug or release mode (in release mode it is more aggressive)

    Tuesday, June 24, 2008 3:08 PM