Reputation: 477230
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)?
Upvotes: 4
Views: 2490
Reputation: 63254
WinDbg + SOS can help understand that. But it takes time to learn that. For example,
Where's your leak at? [Using WinDbg, SOS, and GCRoot to diagnose a .NET memory leak]
Upvotes: 4
Reputation: 28207
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:
Upvotes: 3
Reputation: 6342
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
Upvotes: 2
Reputation: 7260
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.
Upvotes: 4