如何优雅地卸载正在运行线程的子 AppDomain
我有一个服务加载一个子 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();
}
}
}
}
I have a service that loads a child AppDomain and then starts a thread running in it. It needs an AppDomain because it dynamically generates and loads some code and I need to be able to restart it without killing the whole service.
So there is a thread running in an event loop in the child AppDomain, it gets events passed to it through a MarshalByRefObject that sticks stuff in a concurrent queue. I want to stop and unload the child AppDomain and create a new one.
I can simply call Unload on the child AppDomain, but that will abort all the threads and throw a ThrearAbortException. How can I gracefully shut it down? If I set some static flag in the child AppDomain using the MarshalByRefObject then how will the main process be able to wait until its done unloading?
I have some example code that kind of shows how its setup and how I can call Unload to kill it, how could I modify this to allow graceful unloading and never have multiple child 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();
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试以下操作
并且,是的,如果您不首先停止线程,则无法正常卸载 AppDomain。
Try the following
And, yeah, there is no graceful unloading of AppDomain if you didn't stop the threads first.
这种情况本质上与两个 AppDomain 是单独的进程相同,因此您需要使用某种形式的 IPC。一种选择是在要求循环停止时将事件句柄传递到子 AppDomain 中。循环可以在退出之前发出事件信号。等待事件给循环一些时间来完成。如果超时,则可以进行粗略卸载。
The situation is essentially the same as if the two AppDomains were separate processes, so you need to use some form of IPC. One option would be to pass an event handle into the child AppDomain when asking the loop to stop. The loop can signal the event before exiting. Wait for the event to give the loop some time to finish. If you time out, then you can do a rough unload.
序列化所有子 AppDomain。将其发送到远程服务器。关闭该服务器。
Serialize all child AppDomains. Send it to remote server. Turn that server off.