In my earlier post, I have explained how to create AppDomain
inside process and how we can share data between AppDomains. As per request
from one of you, in this post I am going to explain how we can get list of all AppDomains
inside process.
To enumerate all the AppDomains inside process we can use class
called CorRuntimeHost. This class is available inside mscoree namespace and can
be added externally from C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscoree.tlb
location. This class provides EnumDomains method which is used to enumerate AppDomains
inside process. The NextDomain method of this class is used to get next
available AppDomain if no AppDomain found, sets domain to null.
Let’s have a
look on below code snippet.
AppDomain.CreateDomain("AppDomain 1");
AppDomain.CreateDomain("AppDomain 2");
AppDomain.CreateDomain("AppDomain 3");
List<AppDomain>
appDomains = new List<AppDomain>();
IntPtr handle = IntPtr.Zero;
CorRuntimeHost host = new
CorRuntimeHost();
try
{
host.EnumDomains(out handle);
while (true)
{
object domain;
host.NextDomain(handle, out domain);
if (domain == null)
break;
appDomains.Add((AppDomain)domain);
}
}
finally
{
host.CloseEnum(handle);
}
foreach (AppDomain
appDom in appDomains)
{
Console.WriteLine(appDom.FriendlyName);
}
Output –
AppDomain 1
AppDomain 2
AppDomain 3
How to get specific AppDomin from process?
We can get specific AppDomain using the same code but with
little modification. Let’s have a look on below code.
public void GetAppDomain(string name)
{
IntPtr handle = IntPtr.Zero;
CorRuntimeHost host = new
CorRuntimeHost();
try
{
host.EnumDomains(out handle);
while (true)
{
object domain;
host.NextDomain(handle, out domain);
AppDomain myAppDomain = domain as AppDomain;
if (myAppDomain == null)
break;
if (myAppDomain.FriendlyName.Equals(name))
{
Console.WriteLine("AppDomain
Name - {0}", myAppDomain.FriendlyName);
}
}
}
finally
{
host.CloseEnum(handle);
}
}
See Also –