为什么终结器中的AppDomain.Unload()错误? [英] Why does AppDomain.Unload() error in finalizer?

查看:367
本文介绍了为什么终结器中的AppDomain.Unload()错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一些示例代码:

  using System; 
命名空间UnloadFromFinalizer
{
class Program
{
static void Main(string [] args)
{
Program p = new Program( );
}

AppDomain域;
Program()
{
this.domain = AppDomain.CreateDomain(MyDomain);
}

〜Program()
{
AppDomain.Unload(this.domain); //< - 抛出的异常
}




$ b我有一个类在构造函数中创建一个AppDomain,在对象的生命周期中使用。我想正确地清理AppDomain,所以我想我会在终结器中调用Unload。不幸的是,这会导致CannotUnloadAppDomainException被抛出。 AppDomain.Unload 的MSDN文档说明:



在某些情况下,如果在终结器中调用,调用Unload会立即导致CannotUnloadAppDomainException异常。


这是为什么?成员变量域已经被清理了吗?该清理是否会自动包含卸载AppDomain,还是会以某种无法访问的方式存在?有什么我应该做的,或者我可以安全地转储终结器? (我并不在乎GC在什么时候完全清理掉了我的对象。)

解决方案

AppDomain 类没有定义终结器,因此只会像平常一样被垃圾回收。您的 Program 类的终结器将从垃圾收集器的终结器线程中调用。发生这种情况时,不能保证你的 AppDomain 实例将被垃圾回收,因此你将得到未确定的行为。



我不会打扰 Program 的终结器,因为 AppDomain 会被垃圾回收无论如何,此外,当 Main 方法退出时,整个过程将被销毁。


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

解决方案

The AppDomain class does not have a finalizer defined and so will just be garbage collected as normal. The finalizer of your Program class will be called from the finalizer thread of the garbage collector. When this happens, there is no guarantee that your AppDomain 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 the AppDomain will get garbage collected anyway, plus in addition, the whole process will be destroyed when the Main method exits anyway.

这篇关于为什么终结器中的AppDomain.Unload()错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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