我可以生成动态异步方法使用System.Linq.Ex pressions? [英] Can I generate an async method dynamically using System.Linq.Expressions?

查看:173
本文介绍了我可以生成动态异步方法使用System.Linq.Ex pressions?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道编译器不能异步拉姆达前pression转换为前pression树,但它是可以手动生成前pression树?

I know the compiler can't convert an async lambda expression to an expression tree, but is it possible to generate the expression tree manually ?

var expr = Expression.Lambda<Func<Task>>(
     // how do I use 'await' in the body here?
);
var func = expr.Compile();

我找不到异步与的任何方法等待防爆pression 类,但也许有另一种方式?

I can't find any method related to async or await in the Expression class, but perhaps there's another way?

推荐答案

的await 涉及的显著编译器重新编写;生成的IL是相当不同的原来的C#,具有可变悬挂(上一个类)和分支,任务,延续等,这肯定是不是可以重新在的简单拉姆达,尽管最近有更丰富的防爆pression 支持(防爆pression.Block 等)的技术上的我想这大概是可以模仿大多数编译器的事情等待 - 但你可能去挺糊涂试图手工做。

await involves significant compiler re-writing; the generated IL is quite dissimilar to the original C#, with variable hoisting (onto a class) and branching, tasks, continuations, etc. It certainly isn't something that can be represented in a simple lambda, although in recent versions of .NET with richer Expression support (Expression.Block etc), technically I suppose it is probably possible to mimic most of the things the compiler does for await - but you'd probably go quite loopy trying to do it by hand.

没有,据我所知,没有任何设施的自动化的这个翻译存在防爆pression API中,坦白说我不会永远应该会存在。

No, AFAIK, no facility to automate this translation exists in the Expression API, and frankly I wouldn't ever expect there to be.

同样的大概可能是的ILGenerator 的说;坦率地说,据我所知唯一的轻松的方式(我用的是易非常不正确地)使用等待中的元编程将生成C#和运行它通过罗斯林或 CSHARP codeProvider

The same probably could be say of ILGenerator; frankly, AFAIK the only "easy" way (and I use the word "easy" quite incorrectly) to use await in meta-programming would be to generate C# and run it through roslyn or CSharpCodeProvider.

这篇关于我可以生成动态异步方法使用System.Linq.Ex pressions?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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