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

查看:34
本文介绍了为什么 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 文档注释:

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:

在某些情况下,调用 Unload 会导致立即出现 CannotUnloadAppDomainException,如果在终结器中调用它就足够了.

In some cases, calling Unload causes an immediate CannotUnloadAppDomainException, for ample if it is called in a finalizer.

这是为什么?成员变量域"是否已经清理?该清理是否会自动包括卸载 AppDomain,或者它仍会以某种无法访问的方式存在?有什么我应该做的,或者我可以安全地转储终结器吗?(我真的不在乎 GC 何时清除我的对象,只要它在此过程中完全清除即可.)

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

推荐答案

AppDomain 类没有定义终结器,因此只会像往常一样被垃圾收集.Program 类的终结器将从垃圾收集器的终结器线程中调用.发生这种情况时,无法保证您的 AppDomain 实例会或不会被垃圾收集,因此您将获得不确定的行为.

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.

我不会打扰Program的终结器,因为无论如何AppDomain都会被垃圾收集,另外,当>Main 方法无论如何都会退出.

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天全站免登陆