虽然您可以调用将由单独的 AppDomain 处理的委托,但我个人一直使用“CreateInstanceAndUnwrap”方法,该方法在外部应用程序域中创建一个对象并返回一个代理。
为此,您的对象必须继承自 MarshalByRefObject。
这是一个例子:
public interface IRuntime
{
bool Run(RuntimesetupInfo setupInfo);
}
// The runtime class derives from MarshalByRefObject, so that a proxy can be returned
// across an AppDomain boundary.
public class Runtime : MarshalByRefObject, IRuntime
{
public bool Run(RuntimeSetupInfo setupInfo)
{
// your code here
}
}
// Sample code follows here to create the appdomain, set startup params
// for the appdomain, create an object in it, and execute a method
try
{
// Construct and initialize settings for a second AppDomain.
AppDomainSetup domainSetup = new AppDomainSetup()
{
ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile,
ApplicationName = AppDomain.CurrentDomain.SetupInformation.ApplicationName,
LoaderOptimization = LoaderOptimization.MultiDomainHost
};
// Create the child AppDomain used for the service tool at runtime.
childDomain = AppDomain.CreateDomain(
"Your Child AppDomain", null, domainSetup);
// Create an instance of the runtime in the second AppDomain.
// A proxy to the object is returned.
IRuntime runtime = (IRuntime)childDomain.CreateInstanceAndUnwrap(
typeof(Runtime).Assembly.FullName, typeof(Runtime).FullName);
// start the runtime. call will marshal into the child runtime appdomain
return runtime.Run(setupInfo);
}
finally
{
// runtime has exited, finish off by unloading the runtime appdomain
if(childDomain != null) AppDomain.Unload(childDomain);
}
在上面的示例中,它被编码为执行一个'Run'方法,传入一些设置信息,并且确定Run方法的完成表明子AppDomain中的所有代码都已完成运行,所以我们有一个finally确保卸载 AppDomain 的块。
您可能经常需要注意将哪些类型放置在哪些程序集中 - 您可能希望使用一个接口并将其放置在一个单独的程序集中,调用者(我们设置应用程序域的代码,并调用它) ) 和实现者(运行时类)都依赖。此 IIRC 允许父 AppDomain 仅加载包含接口的程序集,而子 appdomain 将加载包含 Runtime 的程序集及其依赖项(IRuntime 程序集)。 IRuntime 接口使用的任何用户定义类型(例如,我们的 RuntimeSetupInfo 类)通常也应该与 IRuntime 放在同一个程序集中。此外,请注意如何定义这些用户定义的类型 - 如果它们是数据传输对象(如 RuntimeSetupInfo 可能是),您可能应该使用 [serializable] 属性标记它们 - 以便传递对象的副本(从父 appdomain 到孩子)。您希望避免将呼叫从一个应用程序域编组到另一个应用程序域,因为这非常慢。按值传递 DTO(序列化)意味着访问 DTO 上的值不会引发跨单元调用(因为子 appdomain 拥有自己的原始副本)。当然,这也意味着值的变化不会反映在父appdomain的原始DTO中。
正如示例中的代码,父 appdomain 实际上最终会同时加载 IRuntime 和 Runtime 程序集,但这是因为在对 CreateInstanceAndUnwrap 的调用中,我使用 typeof(Runtime) 来获取程序集名称和完全限定的类型名称.您可以改为硬编码或从文件中检索这些字符串 - 这将解耦依赖关系。
AppDomain 上还有一个名为“DoCallBack”的方法,看起来它允许调用外部 AppDomain 中的委托。但是,它采用的委托类型是“CrossAppDomainDelegate”类型。其中的定义是:
public delegate void CrossAppDomainDelegate()
因此,它不允许您向其中传递任何数据。而且,由于我从未使用过它,因此我无法告诉您是否有任何特别的问题。
另外,我建议您查看 LoaderOptimization 属性。您将其设置为什么可能会对性能产生重大影响,因为此属性的某些设置会强制新的 appdomain 加载所有程序集(以及 JIT 等)的单独副本,即使 (IIRC) 程序集在 GAC 中(即这包括 CLR 程序集)。如果您使用来自子 appdomain 的大量程序集,这会给您带来可怕的性能。例如,我使用了来自子 appdomains 的 WPF,这导致我的应用程序出现巨大的启动延迟,直到我设置了更合适的加载策略。