问题
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