How to check if AppDomain is unloaded?

心已入冬 提交于 2019-12-22 10:07:18

问题


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.



来源:https://stackoverflow.com/questions/34333238/how-to-check-if-appdomain-is-unloaded

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!