Enumerating AppDomains for a Process

It turns out to not trivial if you want to enumerating the AppDomains, below is the sample code

(The same has been mentioned here and here)

public static IList GetAppDomains()
{
   List appDomains = new List();
   IntPtr enumHandle = IntPtr.Zero;

   CorRuntimeHostClass host = new CorRuntimeHostClass();
   try
   {
      host.EnumDomains(out enumHandle);
      while (true)
      {
         object domain = null;
         host.NextDomain(enumHandle, out domain);
         if (domain == null)
         {
            break; // exits the while (true)
         }
         appDomains.Add((AppDomain)domain);
      }
      return appDomains;
   }
   catch (Exception ex)
   {
      Debug.WriteLine(ex.Message);
      return null;
   }
   finally
   {
      if (host != null)
      {
         host.CloseEnum(enumHandle);
         Marshal.ReleaseComObject(host);
      }
   }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s