List AppDomains in Process

此生再无相见时 提交于 2019-12-17 03:03:39

问题


Is there any possibility how to enumerate AppDomains within Process?


回答1:


You may want to look at this 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);
            }
        } 
    }



回答2:


I refine it as this:

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);
        }
    }
}

Call it as this:

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

Remember to reference COM object \WINDOWS\Microsoft.NET\Framework\vXXX\mscoree.tlb, set reference mscoree "Embed Interop Types" as "False".



来源:https://stackoverflow.com/questions/388554/list-appdomains-in-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!