Visual Studio 2015是否有工具监控运行时创建的对象?
First, let's confirm your initial assumption: you're absolutely right about the Car example. When you run:
Car c = new Car(); c = new Car("black");
Two distinct Car instances are created. The first one loses all references once c is reassigned, so it becomes eligible for garbage collection—but until the GC runs, it does occupy memory.
Now, onto the tools you can use in Visual Studio 2015 to monitor object creation (both .NET and COM objects):
1. Fixing the Memory Usage Tool (Your First Stop)
It sounds like you didn't fully leverage the Memory Usage tab in Diagnostic Tools. Here's how to get it working properly:
- Set breakpoints at key points in your code (e.g., right after both
new Car()lines). - Start debugging (
F5), and when execution hits a breakpoint, click the Take Snapshot button in the Memory Usage tab. - Take a second snapshot after the second
newoperation, then use the Compare Snapshots feature. You'll see the count ofCarinstances increase by 2, and you can drill into each instance to view its allocation stack trace (confirming exactly where it was created). - For orphaned objects (like the first
Car), look for instances with no active references in the References view.
2. CLR Profiler (For Deep .NET Object Tracking)
If the built-in Memory Usage tool isn't detailed enough, use the CLR Profiler (compatible with VS2015). It lets you:
- Track every object allocation in real time, including the exact method/line of code that created it.
- Visualize object lifecycles, so you can see when the first
Carinstance becomes unreachable. - Filter by type to focus only on
Carobjects or COM wrapper objects (__ComObjecttypes).
3. Tools for COM Object Monitoring
COM objects are trickier because of Runtime Callable Wrappers (RCWs) in .NET, but VS2015 has tools to help:
- OLE/COM Object Viewer: Access it via
Tools > OLE/COM Object Viewer(or runoleview.exedirectly). Check the Running Objects node to see all active COM instances in your process. You can also inspect type libraries to understand how COM objects are being instantiated. - Memory Usage + RCW Tracking: In Memory Usage snapshots, look for
__ComObjectinstances. Each represents a wrapped COM object. Check their reference chains to see if any code is holding onto the RCW unnecessarily (preventing the COM object from being released). - Debugger Modules Window: While debugging, open the Modules window (
Ctrl+Alt+U) to load symbols for your COM components. Combined with memory snapshots, this helps trace where COM objects are being created.
Quick Tips for COM Object Leaks
- Always ensure you're properly releasing COM objects: either call
Marshal.ReleaseComObject()when done, or let the GC collect the RCW (though this isn't always immediate). - Use the Immediate Window during debugging to check the reference count of a COM object with
Marshal.GetComObjectData(c, ref count)(adjust syntax as needed for your code).
内容的提问来源于stack exchange,提问作者Masoud Keshavarz

