List AppDomains in Process
是否有可能在进程内枚举AppDomain?
你可能想看看这篇文章
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 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); } } } |
我将其提炼为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 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); } } } |
称之为:
1 2 3 4 | foreach (AppDomain appDomain in EnumAppDomains()) { // use appDomain } |
记住要引用COM对象windowsmicrosoft.netframeworkvxxxmscoree.tlb,请将reference mscoree"embed interop types"设置为"false"。