A host application can monitor the resources that an AppDomain consumes. Some hosts will use this information to decide when to forcibly unload an AppDomain should its memory or CPU con- sumption rise above what the host considers reasonable. Monitoring can also be used to compare the resource consumption of different algorithms to determine which uses fewer resources. Because AppDomain monitoring incurs additional overhead, hosts must explicitly turn the monitoring on
by setting AppDomain’s static MonitoringEnabled property to true. This turns on monitoring for all AppDomains. After monitoring is turned on, it cannot be turned off; attempting to set the MonitoringEnabled property to false causes an ArgumentException to be thrown.
After monitoring is turned on, your code can query the following four read-only properties of- fered by the AppDomain class:
■ MonitoringSurvivedProcessMemorySizeThis static Int64 property returns the number of bytes that are currently in use by all AppDomains controlled by the current CLR instance. The number is accurate as of the last garbage collection.
■ MonitoringTotalAllocatedMemorySizeThis instance Int64 property returns the num- ber of bytes that have been allocated by a specific AppDomain. The number is accurate as of the last garbage collection.
■ MonitoringSurvivedMemorySizeThis instance Int64 property returns the number of bytes that are currently in use by a specific AppDomain. The number is accurate as of the last garbage collection.
■ MonitoringTotalProcessorTimeThis instance TimeSpan property returns the amount of
CPU usage incurred by a specific AppDomain.
The following class shows how to use three of these properties to see what has changed within an AppDomain between two points in time.
private sealed class AppDomainMonitorDelta : IDisposable { private AppDomain m_appDomain;