Sunday, January 28, 2007

Checking for Leaks in Managed Code

Signs that an application is leaking memory:
  • Throwing an OutOfMemoryException
  • Responsiveness is growing very sluggish because it started swapping virtual memory to disk
  • Memory use is gradually (or not so gradually) increasing in Task Manager

Using PerfMon to determine what kind of memory is leaking:

  • Process/Private Bytes
  • .NET CLR Memory/# Bytes in All Heaps
  • .NET CLR LocksAndThreads/# of current logical Threads

The Process/Private Bytes counter reports all memory that is exclusively allocated for a process and can't be shared with other processes on the system. The .NET CLR Memory/# Bytes in All Heaps counter reports the combined total size of the Gen0, Gen1, Gen2, and large object heaps. The .NET CLR LocksAndThreads/# of current logical Threads counter reports the number of logical threads in an AppDomain.

If an application's logical thread count is increasing unexpectedly, thread stacks are leaking. If Private Bytes is increasing, but # Bytes in All Heaps remains stable, unmanaged memory is leaking. If both counters are increasing, memory in the managed heaps is building up.

Adopted from Debug Leaky Apps: Identify And Prevent Memory Leaks In Managed Code by James Kovacs.

Labels: