简体   繁体   English

如何在单独的AppDomain中运行方法?

[英]How to run a method in a separate AppDomain?

In my scenario, I want to execute a method in a separate AppDomain. 在我的场景中,我想在单独的AppDomain中执行一个方法。 How many different ways could I take to achieve this? 可以采取多少种不同的方法来实现这一目标?

Especially, I have the following question: 特别是,我有以下问题:

  • Can I load an assembly into AppDomain A and execute its method in AppDomain B? 我可以将程序集加载到AppDomain A并在AppDomain B中执行其方法吗?
  • It seems I achieve this with AppDomain.DoCallBack Method and CrossAppDomainDelegate . 我似乎用AppDomain.DoCallBack方法CrossAppDomainDelegate实现了这一点 I just cannot figure out how could it make sense to have the assembly and the method in different AppDomains. 我无法弄清楚如何在不同的AppDomain中使用程序集和方法是有意义的。 Is the same assmebly loaded again into the other AppDomain in order to execute the method? 为了执行该方法,是否同样可以再次加载到其他AppDomain中?

In order to execute code in a separate AppDomain, the assembly containing that code has to be loaded into that AppDomain. 为了在单独的AppDomain中执行代码,必须将包含该代码的程序集加载到该AppDomain中。 From there you can call a method in the second AppDomain from your hosting domain using reflection or the "CreateInstance" methods on the AppDomain class. 从那里,您可以使用反射或AppDomain类上的“CreateInstance”方法从您的托管域中调用第二个AppDomain中的方法。

Keep in mind, AppDomains are hard boundaries. 请记住,AppDomains是硬边界。 In order to communicate across the AppDomain boundaries, you will need to use remoting or a true IPC-ish mechanism. 为了跨AppDomain边界进行通信,您需要使用远程处理或真正的IPC-ish机制。

This is a bit dated, but I believe it still applies. 这有点过时了,但我相信它仍然适用。 http://blogs.msdn.com/b/suzcook/archive/2003/06/12/57169.aspx http://blogs.msdn.com/b/suzcook/archive/2003/06/12/57169.aspx

Suzanne Cook had a series of posts related to this subject so it may be worth browsing her archives a bit. Suzanne Cook有一系列与此主题相关的帖子,因此可能值得浏览她的档案。

Check out the "CreateInstance" family of methods on the AppDomain class. 查看AppDomain类的“CreateInstance”系列方法。 In the past I've used CreateInstanceFromAndUnwrap() quite a bit for this type of situation. 在过去,我对这种情况使用了CreateInstanceFromAndUnwrap()

As far as your question about how many ways there are to do this... Um, many, but it depends a lot on the exact situation and what objects you have in hand. 至于你关于有多少种方法可以做到这一点的问题...嗯,很多,但这在很大程度上取决于具体情况以及你掌握的对象。

添加Rob的正确答案,我想提一下,任何不使用反射调用的尝试都会导致程序集被加载到您的调用AppDomain中,这可能是您要避免的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM