简体   繁体   English

如何在新AppDomain中从加载到引用的程序集运行方法

[英]How to run method from assembly loaded to references, in new AppDomain

Recently i discover that running few instances of method compiled to .exe is faster than running the same method in fe few new Tasks. 最近,我发现运行少数几个编译为.exe的方法实例比运行少量新任务中的相同方法要快。 I don't know if that applies to every method, but it does to getting data from API. 我不知道这是否适用于所有方法,但确实适用于从API获取数据。

I was searching internet to find answer how to manage that. 我正在搜索互联网以找到解决方法。 I got answers to try run method in new appDomains. 我得到了尝试在新的appDomains中运行方法的答案。 So i create .exe assembly with methods that i want to be run (it is Console application). 因此,我使用要运行的方法(这是控制台应用程序)创建.exe程序集。 I Load it by right click on References -> Add Reference. 我通过右键单击引用->添加引用来加载它。 I could easily access that method by exeName.ClassName.Method(params). 我可以通过exeName.ClassName.Method(params)轻松访问该方法。 The thing is that I don't know how to run this methods in new appDomains. 问题是我不知道如何在新的appDomains中运行此方法。 Every answer that i found in web was with loaded assembly by path. 我在网上找到的每个答案都是按路径加载程序集。

I will also be very happy for answers other than creating AppDomain. 除了创建AppDomain之外,我也会很高兴获得答案。 I just want to pass data to this method and get results. 我只想将数据传递给此方法并获得结果。

TL;DR: Method run in Parallel.For(0,4,i=> method()) works slower than run the same method in 4 instances of compiled .exe file. TL; DR:在Parallel.For(0,4,i => method())中运行的方法比在4个已编译的.exe文件实例中运行相同的方法要慢。

You could use a multi process architecture using IPC protocol or host your methods inside different domains. 您可以使用使用IPC协议的多进程体系结构,也可以将方法托管在不同的域中。 In both situations i recommend .net remoting over wcf because you would write almost the same code for both aproaches and because for talking to a class found in another app domain hosted in the same process, .net remoting is the only way (sadly for many devs but not for me). 在这两种情况下,我都建议通过wcf进行.net远程处理,因为您会为两种方式编写几乎相同的代码,并且因为与同一个进程中托管的另一个应用程序域中的类进行交谈,.net远程处理是唯一的方法(对许多人而言,这是非常遗憾的)开发人员,但不适合我)。 BUT I am almost sure that generally this would NOT be more faster than just creating some threads and calling them asinchronous. 但是我几乎可以肯定,通常这不会比仅创建一些线程并异步调用它们更快。 Inter domains / process communication must rely on message serialization/ deserialization that adds huge overhead, specially if the method call itself is very light. 域间/进程间的通信必须依赖消息序列化/反序列化,这会增加大量开销,尤其是在方法调用本身非常轻巧的情况下。

After some researching and asking i found solution: 经过一番研究和询问,我找到了解决方案:

var ad = AppDomain.CreateDomain("mydomain");
ad.DoCallBack(() =>
            {
                //stuff to do
            }

Probably there'll be some issues with passing data to new AppDomain. 将数据传递到新的AppDomain可能会出现一些问题。 Easiest way for me is: 对我来说最简单的方法是:

ad.SetData("key", value);

and to retrive in AppDomain: 并在AppDomain中检索:

var value = (valueType)AppDomain.CurrentDomain.GetData("key");

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

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