如何检查 AppDomain 是否已卸载? [英] How to check if AppDomain is unloaded?

查看:42
本文介绍了如何检查 AppDomain 是否已卸载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过代理在另一个 AppDomain 中使用了一堆对象.它们位于一个单独的域中,因为我需要热交换包含这些对象的程序集,所以我在使用完它托管的程序集后卸载了 AppDomain.

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.

有时我想检查一下我过去是否卸载了 AppDomain(或者它以某种方式自行卸载或其他原因)以进行测试.有没有办法做到这一点?

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?

显而易见的方法是做一些会抛出 AppDomainUnloadedException 的事情,但我希望有其他方法.

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

推荐答案

我相信你可以在一些给定的Dictionary中组合使用AppDomain的存储引用/code> 其中 bool 在其加载或卸载时所在的位置,并处理 AppDomain.DomainUnload 事件.

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);

这样您就可以检查 AppDomain 是否已卸载:

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

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

或者,您可以使用 AppDomain.Id 作为键:

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);

...if 语句如下所示:

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

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

这篇关于如何检查 AppDomain 是否已卸载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆