在进程中列出AppDomain

有没有可能如何枚举过程中的AppDomain?

你可能想看看这个post

using System.Runtime.InteropServices; // Add the following as a COM reference - C:\WINDOWS\Microsoft.NET\Framework\vXXXXXX\mscoree.tlb using mscoree; 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); } } } 

我将其细化为:

 using System.Runtime.InteropServices; using mscoree; public static IEnumerable<AppDomain> EnumAppDomains() { IntPtr enumHandle = IntPtr.Zero; ICorRuntimeHost host = null; try { host = new CorRuntimeHostClass(); host.EnumDomains(out enumHandle); object domain = null; host.NextDomain(enumHandle, out domain); while (domain != null) { yield return (AppDomain)domain; host.NextDomain(enumHandle, out domain); } } finally { if (host != null) { if (enumHandle != IntPtr.Zero) { host.CloseEnum(enumHandle); } Marshal.ReleaseComObject(host); } } } 

这样称呼它:

 foreach (AppDomain appDomain in EnumAppDomains()) { // use appDomain } 

请记住引用COM对象\ WINDOWS \ Microsoft.NET \ Framework \ vXXX \ mscoree.tlb,将引用mscoree“Embed Interop Types”设置为“False”。