views:

132

answers:

4

I'm trying to optimize memory usage of a program and therefore wants to remove objects when they aren't needed any longer. To check if this works correctly I wrote a console.writeline method in the destructor of the type of object I want to remove. However when I test the program, no lines are written (only when the program terminates of course).

Is there a way to get a list of object, events,... That keep a certain object alive and prevent it from being eliminated by the garbage collector. Or is there a profiler, debugger that can do this (MonoDevelop-compatible if possible)?

+3  A: 

cleanup occurrence is controlled by system, if your memory allocation is small enough and system didn't think it is necessary to cleanup than your destructor wont be called. it is not a best practice for production but you can force the GC by GC.Collect() use it only on test. If your destructor isn't call then there might be a leak.

i don't know profiler in mono environtment but this profiler is good enough in windows.

ktutnik
Be careful not to use GC.Collect() as a general purpose cleanup tool. It can actually make memory usage _worse_ by moving objects that aren't ready for collection yet to a higher-order generation, such that they're harder to collect in the future.
Joel Coehoorn
@Joel Coehoorn, absolutely agree! i wrote it is not best practice for production and in case if you want your destructor called by GC.
ktutnik
+1  A: 

Deallocating resources takes resources. If the garbage collector doesn't detect that too much memory is being used, it won't free its resources. If you need a deterministic "destructor," implement IDisposable. See also the "using" keyword

bowenl2
IDisposable and using won't ever release any memory (unless of course that memory is held by unmanaged (external) code).
Joel Coehoorn
+2  A: 

WinDbg + SOS can help understand that. But it takes time to learn that. For example,

http://blogs.msdn.com/b/delay/archive/2009/03/11/where-s-your-leak-at-using-windbg-sos-and-gcroot-to-diagnose-a-net-memory-leak.aspx

Lex Li
+2  A: 

The .NET garbage collector will automatically clean up (free) objects that aren't referenced any more. However, it is not uncommon for programs to have static fields, unremoved event handlers, or other references that cause objects to be kept alive (and using memory) longer than is strictly necessary.

To fix this, use a memory profiler that will identify the "roots" holding your objects, figure out why they're still referenced, and fix the bug causing the object to still be referenced.

Some commercial and free memory profilers are:

Bradley Grainger