views:

59

answers:

1

Hi,

I know this was answered before, but I'd like to pose a somewhat different question.

Is there any conceivable way to implement GC.GetAliveInstancesOf(), that can be evaluated in Visual Studio Debug Watch window? Sasha Goldstein shows one solution in this article, but it requires every class you want to query inherit from a specific base class.

I'll emphasize that I only want to use this method during debugging, so I don't care that the GC may change an object's address in memory during runtime.

One idea might be to somehow harness the !dumpheap –type command of SOS, and do some magic trick to create a temporary variable and have it point out to the memory address printed by SOS.

Does anyone have a solution that works?

+1  A: 

There is just about nothing that could drag down the garbage collector more than it having to second-guess that some kind of user code could be interested in finding roots that it doesn't own. Keeping it as snappy as possible is crucial. For that matter, the only way you could ever see what is being referenced with some kind of confidence is to freeze all threads that might be allocating memory from the garbage collected heap.

Well, that's possible, debuggers do that. You already know the way Windbg does it. It however wasn't designed to be a tool that was optimized to track managed objects. There are other tools that were: memory profilers. Plenty to choose from, don't try to build your own. From the freeware (and time-wasting) CLR Profiler, to the 3rd party offerings like Ants and dotTrace and many others. A couple of hundred bucks to solve your problem, there is no way you can do better by yourself for less.

Hans Passant
I don't want to roll my own memory profiler. I want to take an address of an object on the managed heap (that I can get with a tool like windbg), and then somehow get that variable in Visual Studio's Debug Watch window, when all threads are stopped. I didn't understand from your answer whether you think it's impossible or not, and why.
Omer Raviv
Having the address of a GC object is of no use. The garbage collector will move it sooner or later (you don't know when) and you don't know the address anymore. Unless you have a reference to it that the collector updates.
Hans Passant
Is there a risk that the GC will move the address around while the application is halted at a breakpoint, while evaluating some expression or something like that? If not, then I don't care... Assuming this method will be called from the Debug Watch window, I'll be forced to re-evaluate the method call the next time I break into the debugger anyways.
Omer Raviv
No, the collector can't run when the debugger stopped the program. I suppose you'll want to do whatever you did to get the address the 1st time again the 2nd time.
Hans Passant