.net - 队列任务调度程序 : How to deal with AppDomain unload?

标签 .net task-parallel-library appdomain parallel-extensions

使用 ParallelExtensionsExtras 中的 QueuedTaskScheduler我面临以下问题:当运行调度程序线程的 AppDomain 被卸载时(在我的例子中是由于将新代码版本部署到 ASP.NET 站点),线程进入无限旋转循环。相关代码是这样的:

// If a thread abort occurs, we'll try to reset it and continue running.
while (true)
{
    try
    {
        // For each task queued to the scheduler, try to execute it.
        foreach (var task in _blockingTaskQueue.GetConsumingEnumerable(_disposeCancellation.Token))
        {
            //[...] run task
        }
    }
    catch (ThreadAbortException)
    {
        // If we received a thread abort, and that thread abort was due to shutting down
        // or unloading, let it pass through.  Otherwise, reset the abort so we can
        // continue processing work items.
        if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload())
        {
            Thread.ResetAbort();
        }
    }
}

调度程序尝试检测其 AppDomain 正在卸载的情况,但不幸的是,写入的条件在运行时被证明是错误的。这会导致中止被重置并继续循环。

我了解不会立即引发挂起的中止。只是有时 jitted 代码会轮询挂起的中止并引发 TAE。根据我观察到的调用堆栈,这似乎在此处的 GetConsumingEnumerable 中。

因此线程永远不会退出循环并继续旋转。 (即使这种解释是错误的,线程也可以证明最终会进入 GetConsumingEnumerable 并在那里消耗大量 CPU)。

此代码的适当修复是什么? 似乎无法检测到当前 AppDomain 正在卸载(AppDomain.CurrentDomain.IsFinalizingForUnload 可能是 false因为我们还没有完成)。我考虑修改代码以从不重置中止(这解决了问题)。但什么才是合适的解决方案?

(我对变通办法不太感兴趣,因为我已经有了变通办法。)

最佳答案

你有没有试过这样的东西(未经测试)?

var domain = Thread.GetDomain();
var unloading = false;
domain.DomainUnload += (s, e) =>
{
    unloading = true;
    _blockingTaskQueue.CompleteAdding();
};

while (true)
{
    try
    {
        // For each task queued to the scheduler, try to execute it.
        foreach (var task in _blockingTaskQueue.GetConsumingEnumerable(_disposeCancellation.Token))
        {
            //[...] run task
        }
    }
    catch (ThreadAbortException)
    {
        if (!unloading)
        {
            Thread.ResetAbort();
        }
    }
}

已更新,我不确定 ASP.NET,但以下内容会在控制台应用程序中产生正确的事件序列。我没有看到 "End of DoCallBack",即使我调用了 Thread.ResetAbort()。我想这是有道理的,因为 DoCallBack 中的代码应该只在不再存在的域上执行:

using System;
using System.Runtime.Remoting.Contexts;
using System.Threading;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var newDomain = System.AppDomain.CreateDomain("New domain");
            var thread = new Thread(() =>
            {
                try
                {
                    newDomain.DoCallBack(() =>
                    {
                        var unloading = false;
                        try
                        {
                            var domain = Thread.GetDomain();
                            domain.DomainUnload += (s, e) =>
                            {
                                unloading = true;
                                // call CompleteAdding here
                                Console.WriteLine("domain.DomainUnload");
                            };

                            Thread.Sleep(2000);
                            Console.WriteLine("End of sleep");
                        }
                        catch (ThreadAbortException)
                        {
                            Console.WriteLine("ThreadAbortException");
                            Thread.ResetAbort();
                        }

                        Console.WriteLine("End of DoCallBack");
                    });
                }
                catch (AppDomainUnloadedException)
                {
                    Console.WriteLine("AppDomainUnloadedException");
                }
                Console.WriteLine("End of thread");
            });

            thread.Start();
            Thread.Sleep(1000);
            AppDomain.Unload(newDomain);

            Console.ReadLine();
        }
    }
}

输出:

domain.DomainUnload
ThreadAbortException
AppDomainUnloadedException
End of thread

关于.net - 队列任务调度程序 : How to deal with AppDomain unload?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23310872/

相关文章:

c# - 如何在 C# UWP 中暂停一个线程,同时继续其他线程

c# - 为什么这个并行代码比类似的非并行版本慢?

c# - 使用异步和等待

c# - 如何将不可序列化的对象作为参数发送给代理方法。 MarshalByRefObject 包装器?

c# - 如何检查 AppDomain 是否已卸载?

c# - 如何从 .NET Framework 调用 .NET Core 程序集中的方法

c# - 为什么 "new CultureInfo("xx")"在一种环境中引发异常,而在另一种环境中则不会?

.net - Visual Studio 版本和 .NET 目标版本

c# - 从文件扩展名获取 ImageFormat

.net - 何时以及何时不安装到 GAC 中?