是否可以序列化的C#代码块? [英] Is it possible to serialize a C# code block?

查看:229
本文介绍了是否可以序列化的C#代码块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C#与 .NET 3.5 的。 ?是否有可能要序列化的代码块,地方传送它,反序列化,然后执行它。

I'm using C# with .NET 3.5. Is it possible to serialize a block of code, transmit it somewhere, deserialize it, and then execute it?

这方面的一个例子用法是:

An example usage of this would be:

Action<object> pauxPublish = delegate(object o)
{
    if (!(o is string))
    {
        return;
    }
    Console.WriteLine(o.ToString());
};
Transmitter.Send(pauxPublish);

通过一些远程程序做的:

With some remote program doing:

var action = Transmitter.Recieve();
action("hello world");



我的最终目标是能够在不同的进程来执行任意代码(没有先验知识的代码)。

My end goal is to be able to execute arbitrary code in a different process (which has no prior knowledge of the code).

推荐答案

YES !!!

我们已经为表现一个很现实的情况下做到了这一点。在运行时执行此操作或使用DSL不是由于性能的选项。

We have done this for a very real case of performance. Doing this at runtime or using a DSL was not an option due to performance.

我们将代码编译成汇编,并撕开IL出来的方法。然后我们用这种方法相关联的所有元数据,并通过XML序列化全乱了,压缩它,并把它放在我们的数据库。

We compile the code into an assembly, and rip the IL out of the method. We then get all the metadata associated with this method and serialize the whole mess via XML, compress it, and put it in our database.

在再水化时,我们重新构成使用在 DynamicMethod的类中的IL和元数据,并执行它。

At re-hydration time, we re-constitute the IL with the metadata using the DynamicMethod class, and execute it.

我们这样做是因为速度快。我们有成千上万的小代码块。不幸的是,编译的代码块,并在飞行至少需要250毫秒,这是太慢了我们运行它。我们采取了这种方法,并且它的工作真的很好。在运行时,它需要时间来重建的方法和运行它的不可测量。

We do this because of speed. We have thousands of little blocks of code. Unfortunately, to compile a block of code and run it on the fly takes at least 250 ms, which is way too slow for us. We took this approach, and it is working REALLY well. At run-time, it takes an unmeasurable amount of time to reconstitute the method and run it.

只是为了保持眼睛...签名组件和未签名组件的事情不能混用序列化方法的数据。

Only thing to keep an eye on... Signed assemblies and Unsigned assemblies cannot mix the serialized method data.

这篇关于是否可以序列化的C#代码块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆