How to check if AppDomain is unloaded?

2019-05-11 18:14发布

问题:

I'm using a bunch of objects in another AppDomain through proxy. They are in a separate domain because I need to hot-swap assemblies that contain those objects, so I Unload an AppDomain after I'm done using the assemblies it's hosting.

I want to check sometimes if I've unloaded an AppDomain in the past (or it somehow got unloaded on its own or something) for testing purposes. Is there a way to do this?

The obvious way is to do something that would throw an AppDomainUnloadedException, but I'm hoping there is some other way.

回答1:

I believe that you can use a combination of storing references of AppDomain in some given Dictionary<AppDomain, bool> where the bool is if its loaded or unloaded, and handle AppDomain.DomainUnload event.

Dictionary<AppDomain, bool> appDomainState = new Dictionary<AppDomain, bool>();

AppDomain appDomain = ...; // AppDomain creation
appDomain.DomainUnload += (sender, e) => appDomainState[appDomain] = false;
appDomainState.Add(appDomain, true);

This way you'll be able to check if an AppDomain is unloaded:

// "false" is "unloaded"
if(!appDomainState[appDomainReference]) 
{
}

Alternatively, you can use AppDomain.Id as key:

Dictionary<int, bool> appDomainState = new Dictionary<int, bool>();

AppDomain appDomain = ...; // AppDomain creation
appDomain.DomainUnload += (sender, e) => appDomainState[appDomain.Id] = false;
appDomainState.Add(appDomain.Id, true);

...and the if statement would look as follows:

// "false" is "unloaded"
if(!appDomainState[someAppDomainId]) 
{
}


回答2:

You can list all appdomains in your program with the code from this stackoverflow link. Then you can compare them by ID or FriendlyName or something similar.