为什么 AppDomain.Unload() 在终结器中出错?
下面是一些示例代码:
using System;
namespace UnloadFromFinalizer
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
}
AppDomain domain;
Program()
{
this.domain = AppDomain.CreateDomain("MyDomain");
}
~Program()
{
AppDomain.Unload(this.domain);//<-- Exception thrown here
}
}
}
我有一个类,它在构造函数中创建一个 AppDomain,以便在对象的生命周期内使用。我想正确清理 AppDomain,所以我想我应该在终结器中调用 Unload。不幸的是,这会导致抛出 CannotUnloadAppDomainException 。 AppDomain.Unload 的 MSDN 文档指出:
在某些情况下,调用 Unload 会立即导致 CannotUnloadAppDomainException,例如在终结器中调用它时。
这是为什么呢?成员变量“domain”是否已经清理干净了?该清理是否自动包括卸载 AppDomain,或者它仍然以某种无法访问的方式存在?我应该做些什么,或者我可以安全地转储终结器吗? (我并不关心 GC 何时删除我的对象,只要它在此过程中被完全清理即可。)
Here's some sample code:
using System;
namespace UnloadFromFinalizer
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
}
AppDomain domain;
Program()
{
this.domain = AppDomain.CreateDomain("MyDomain");
}
~Program()
{
AppDomain.Unload(this.domain);//<-- Exception thrown here
}
}
}
I have a class that creates an AppDomain in the constructor to be used over the lifetime of the object. I'd like to properly cleanup the AppDomain, so I thought I would call Unload in the finalizer. Unfortunately, that causes a CannotUnloadAppDomainException to be thrown. The MSDN documentation for AppDomain.Unload notes:
In some cases, calling Unload causes an immediate CannotUnloadAppDomainException, for ample if it is called in a finalizer.
Why is this? Is the member variable "domain" already cleaned up? Does that cleanup automatically include unloading the AppDomain, or will it still exist in some unreachable way? Is there something I should be doing, or can I safely just dump the finalizer? (I don't really care when the GC gets rid of my object so long as it's fully cleaned up in the process.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
AppDomain
类没有定义终结器,因此只会像平常一样被垃圾收集。您的Program
类的终结器将从垃圾收集器的终结器线程中调用。发生这种情况时,无法保证您的AppDomain
实例会或不会被垃圾回收,因此您将得到不确定的行为。我不会打扰
Program
的终结器,因为AppDomain
无论如何都会被垃圾收集,此外,当Main< /code> 方法无论如何都会退出。
The
AppDomain
class does not have a finalizer defined and so will just be garbage collected as normal. The finalizer of yourProgram
class will be called from the finalizer thread of the garbage collector. When this happens, there is no guarantee that yourAppDomain
instance will or will not have been garbage collected yet and so you will get undetermined behaviour.I would not bother with the finalizer of
Program
, as theAppDomain
will get garbage collected anyway, plus in addition, the whole process will be destroyed when theMain
method exits anyway.