Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to know what keeps objects alive in C#

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)?

like image 889
Willem Van Onsem Avatar asked Dec 12 '22 20:12

Willem Van Onsem


2 Answers

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]

like image 166
Lex Li Avatar answered Jan 13 '23 06:01

Lex Li


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.

like image 38
ktutnik Avatar answered Jan 13 '23 06:01

ktutnik