Enumerating AppDomains

Recently I was writing a sample app showing some new MAF (Managed Add-In Framework) features that will be released very soon. Stay tuned.

As I was showing isolation and unload-ability, I wanted to enumerate the AppDomain's in the current process. Surprisingly there is no managed API in the BCL to show AppDomains L Using Interop however, we can list the AppDomains.

using System.Runtime.InteropServices; // for domain enum

using mscoree; // for domain enum. Add the following as a COM reference - C:\WINDOWS\Microsoft.NET\Framework\vXXXXXX\mscoree.tlb

namespace MyNS

{

public class ListProcessAppDomains

{

public static IList<AppDomain> GetAppDomains()

{

IList<AppDomain> _IList = new List<AppDomain>();

IntPtr enumHandle = IntPtr.Zero;

CorRuntimeHostClass host = new mscoree.CorRuntimeHostClass();

try

{

host.EnumDomains(out enumHandle);

object domain = null;

while (true)

{

host.NextDomain(enumHandle, out domain);

if (domain == null) break;

AppDomain appDomain = (AppDomain)domain;

_IList.Add(appDomain);

}

return _IList;

}

catch (Exception e)

{

Console.WriteLine(e.ToString());

return null;

}

finally

{

host.CloseEnum(enumHandle);

Marshal.ReleaseComObject(host);

}

}

}