是否有可能如何在进程内枚举AppDomains?
你可能想看看这篇文章
using System.Runtime.InteropServices; // Add the following as a COM reference - C:\WINDOWS\Microsoft.NET\Framework\vXXXXXX\mscoree.tlb using mscoree; public static IListGetAppDomains() { IList _IList = new List (); 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 IEnumerableEnumAppDomains() { 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".