How? Just consider the rate of change in memory over time for a C# application. As long as the rate of memory allocation is faster than the rate of memory recovery (which is what the garbage collector does), all our available memory will eventually be allocated.
As proof, look at the following memory profile of a C# application that is leaking memory at a rate of 100K bytes per second.
Code Listing
Here is the code with the leak:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Program { private static Queue queue = new Queue(); static void Main(string[] args) { int factor = 100; int i=0; do { Thread.Sleep(1000); var v = new byte[factor * 1024]; queue.Enqueue(v); v = null; Console.WriteLine("i={0}", ++i); } while (true); } } |
Notice line 14 where the programmer wanted to let the Garbage Collector (GC) know that it is alright to reclaim the object by setting its value to null. But the GC will not be able to do so because there is still another reference to the object inside the queue container.
When an container holds references longer than necessary, memory consumption will increase and (in this example) eventually results in an OutOfMemoryException.
In a future post, I hope to be able to show a more complicated memory leak that occurs with event handlers.

No comments:
Post a Comment