Search code examples
c#.netappdomain

How to check if AppDomain is unloaded?


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.


Solution

  • 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]) 
    {
    }