如何优雅地卸载正在运行线程的子 AppDomain

2024-01-05

我有一个服务加载一个子 AppDomain,然后启动一个在其中运行的线程。它需要一个 AppDomain,因为它动态生成并加载一些代码,并且我需要能够在不终止整个服务的情况下重新启动它。

因此,有一个线程在子 AppDomain 的事件循环中运行,它通过将内容粘贴到并发队列中的 MarshalByRefObject 获取传递给它的事件。我想停止并卸载子 AppDomain 并创建一个新的。

我可以简单地对子 AppDomain 调用 Unload,但这将中止所有线程并抛出 ThrearAbortException。我怎样才能优雅地关闭它?如果我使用 MarshalByRefObject 在子 AppDomain 中设置一些静态标志,那么主进程如何能够等到其完成卸载?

我有一些示例代码,展示了它的设置方式以及如何调用 Unload 来终止它,我如何修改它以允许正常卸载并且永远不会有多个子 AppDomains?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.Security.Permissions;
using System.Reflection;
using System.Threading;

namespace TestAppDomains
{
    /// <summary>
    /// Calls to methods magically get transfered to the appdomain it was created in because it derives from MarshalByRefObject
    /// </summary>
    class MarshalProxy : MarshalByRefObject
    {
        public AppDomain GetProxyAppDomain()
        {
            return AppDomain.CurrentDomain;
        }

        public void SayHello()
        {
            Console.WriteLine("MarshalProxy in AD: {0}", AppDomain.CurrentDomain.FriendlyName);
        }

        public void RunLoop()
        {
            try
            {
                while (true)
                {
                    Console.WriteLine("RunLoop {0} in {1}", DateTime.Now.ToLongTimeString(), AppDomain.CurrentDomain.FriendlyName);
                    Thread.Sleep(1000);
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("You killed me! {0}", ex);
                Thread.Sleep(200); //just to make sure the unload is really blocking until its done unloading
                // if the sleep is set to 2000 then you will get a CannotUnloadAppDomainException, Error while unloading appdomain. (Exception from HRESULT: 0x80131015) thrown from the .Unload call
            }
        }

        static int creationCount = 1;
        public static MarshalProxy RunInNewthreadAndAppDomain()
        {
            // Create the AppDomain and MarshalByRefObject
            var appDomainSetup = new AppDomainSetup()
            {
                ApplicationName = "Child AD",
                ShadowCopyFiles = "false",
                ApplicationBase = Environment.CurrentDirectory,
            };

            var childAppDomain = AppDomain.CreateDomain(
                "Child AD " + creationCount++,
                null,
                appDomainSetup,
                new PermissionSet(PermissionState.Unrestricted));

            var proxy = (MarshalProxy)childAppDomain.CreateInstanceAndUnwrap(
                typeof(MarshalProxy).Assembly.FullName,
                typeof(MarshalProxy).FullName,
                false,
                BindingFlags.Public | BindingFlags.Instance,
                null,
                new object[] { },
                null,
                null);

            Thread runnerThread = new Thread(proxy.RunLoop);
            runnerThread.Name = "MarshalProxy RunLoop";
            runnerThread.IsBackground = false;
            runnerThread.Start();

            return proxy;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("I am running in AD: {0}", AppDomain.CurrentDomain.FriendlyName);

            var proxy = MarshalProxy.RunInNewthreadAndAppDomain();
            proxy.SayHello();

            while (true)
            {
                Console.WriteLine("Press enter to kill and restart proxy");
                Console.WriteLine();
                Console.ReadLine();

                Console.WriteLine("Unloading");
                AppDomain.Unload(proxy.GetProxyAppDomain());
                Console.WriteLine("Done unloading");

                proxy = MarshalProxy.RunInNewthreadAndAppDomain();
            }
        }
    }
}

尝试以下操作

runnerThread.IsBackground = true;

是的,如果您不先停止线程,就无法正常卸载 AppDomain。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何优雅地卸载正在运行线程的子 AppDomain 的相关文章

随机推荐