CLR Memory Diagnostics Enables you to Automate Inspection Tasks
Microsoft recently released Microsoft.Diagnostics.Runtime component shortly called as ClrMD via the NuGet Package Manager that allows you to automate inspection tasks and access even more debugging information. It is a set of advanced APIs for programmatically inspecting a crash dump of a .NET program much in the same way as the SOS Debugging Extensions (SOS.dll) and it provides you an ability to write automated crash analysis for your applications and automate many common debugger tasks.
In order to work with ClrMD component, you need to create an instance of DataTarget class, which represents either a crash dump or a live .NET process. After that you have to call TryGetDacLocation() method that attempts to find a matching DAC on the same machine. However, you can also copy the DAC from a machine where a matching CLR is installed if you need to inspect a process for which you do not have a matching CLR by providing the path to the alternate mscordacwks.dll to the CreateRuntime() method manually.
You can then make use of the runtime object to inspect the contents of the GC heap which produces an output as shown below
23B1D30 36 System.Security.PermissionSet
23B1D54 20 Microsoft.Win32.SafeHandles.SafePEFileHandle
23B1D68 32 System.Security.Policy.PEFileEvidenceFactory
23B1D88 40 System.Security.Policy.Evidence
You now have the required data to output a set of heap statistics that can be done by using a LINQ query to group the heap by type and sort by total object size. The resulting output will look like as shown below
564 11 System.Int32
616 2 System.Globalization.CultureData
680 18 System.String
728 26 System.RuntimeType
790 7 System.Char
5,788 165 System.String
17,252 6 System.Object
ClrMD also enables you to retrieve general information about the GC heap, walks the CLRs handle table, application domains in the process and identifies which modules are loaded into them. It also enumerates threads, callstacks of those threads, the last thrown exception on threads and object roots of the process in addition to gathering of data about the various heaps that the .NET runtime make use of. The IntelliSense included with the ClrMD package component enables you to explore the various complicated properties and functions.
In addition to the above features, ClrThread object also contains a CurrentException property whuch may be null and contains the full stack trace, message and type of the exception thrown. If not null then it will contain the last thrown exception on this thread.
Gabriel Gonzalez Nov 22, 2014