AppDomain.Unload 在终结器中抛出? [英] AppDomain.Unload throws in Finalizer?

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

问题描述

所以这是到目前为止的故事,我有一个使用 AppDomain 执行某些任务的工人东西.该域的设置和拆除成本很高.所以我为每个线程创建一个 WeakReference 对象的缓存给工作人员,就像这样:

So here is the story so far, I have this worker thingy which uses an AppDomain to perform some task. The domain is expensive to setup and teardown. So I create a cache per-thread of WeakReference objects to the worker thingy like so:

class Worker
{
    [ThreadStatic]
    static Dictionary<string, WeakReference> _workers;

    public static Worker Fetch( ... ) { you get the idea }

    private AppDomain _domain;
    public Worker(...)
    {
        _domain = AppDomain.Create( ... );
    }

    ~Worker()
    { 
        AppDomain.Unload(_domain);
    }

    // bla bla bla
}

我遇到的问题是,当 GC 收集时,似乎总是在对 AppDomain.Unload 的调用中抛出异常:

The problem I'm having is that seems to always throw an exception in the call to AppDomain.Unload when GC collects:

System.CannotUnloadAppDomainException: Error while unloading appdomain. (Exception from HRESULT: 0x80131015)"

所以我认为这很奇怪,我知道我没有在该域中运行"任何东西...这是怎么回事?经过一番挖掘和反复试验,我想出了这个:

So I'm thinking that's wierd, I know I don't have anything 'running' in that domain... Whats the deal? A bit of digging and trial and error I came up with this:

    ~Worker()
    { 
        new Action<AppDomain>(AppDomain.Unload)
            .BeginInvoke(_domain, null, null);
    }

所以我的问题是:

  1. AppDomain.Unload 是否总是从终结器失败?为什么?
  2. 通过上述解决方法,我会遇到任何不受欢迎"的事情吗?

推荐答案

AppDomains 由单独的 CLR 线程卸载.当终结器线程正在运行时,该线程无法运行.您收到异常是因为 CLR 注意到卸载线程没有取得进展.它永远不会运行,因为终结器线程在 Unload 调用中被阻塞.

AppDomains are unloaded by a separate CLR thread. That thread cannot run while the finalizer thread is running. You're getting the exception because the CLR notices that the unload thread isn't making progress. It never gets going because the finalizer thread is blocked on the Unload call.

死锁.

您的解决方法确实解决了这个僵局.显式卸载而不是依赖终结器是这里更好的方法.

Your workaround indeed solves that deadlock. Doing the unloading explicitly instead of relying on a finalizer is the better approach here.

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

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