Last post Jun 24, 2008 03:08 PM by joteke
Jun 24, 2008 01:56 PM|Saturday3AM|LINK
I have made a function creating a simple graph.
public static System.Drawing.Bitmap Graph(int values, int width, int height)
Bitmap bitmap = new Bitmap(width, height);
Graphics graphics = Graphics.FromImage(bitmap);
// create graph here
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
Jun 24, 2008 02:28 PM|joteke|LINK
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
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).
Jun 24, 2008 02:56 PM|Saturday3AM|LINK
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.
Jun 24, 2008 03:08 PM|joteke|LINK
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 .
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)