3

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.

GregRos
  • 8,667
  • 3
  • 37
  • 63
  • Some programmers try entirely too hard to avoid using a *bool* variable. There is no "or something". – Hans Passant Dec 17 '15 at 11:47
  • 1
    @HansPassant Since it's for testing purposes there is usually an *or something*, even if you're adamantly certain there shouldn't be. – GregRos Dec 17 '15 at 11:50

2 Answers2

3

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]) 
{
}
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
  • Thank you for the suggestion. I will do this if there is no direct way to check if the domain has been unloaded (since it's for testing purposes, the fewer failure points, the better). – GregRos Dec 17 '15 at 11:29
  • @GregRos No problem. If I'm not mistaken, this will be your best bet. Obviously, you might change how you store the `AppDomain` state: it can be a dictionary as I suggested you, a list of classes using a custom type `AppDomainState` which might have a property `Unloaded`... – Matías Fidemraizer Dec 17 '15 at 11:30
1

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.

Community
  • 1
  • 1
Dieter Meemken
  • 1,937
  • 2
  • 17
  • 22