Async lambda to Expression>

2019-06-16 18:10发布

问题:

It is widely known that I can convert ordinary lambda expression to Expression<T>:

Func<int> foo1 = () => 0; // delegate compiles fine
Expression<Func<int>> foo2 = () => 0; // expression compiles fine

How could I do the same with async lambda? I've tried the following analogy:

Func<Task<int>> bar1 = async () => 0; // also compiles (async lambda example)
Expression<Func<Task<int>>> bar2 = async () => 0; // CS1989: Async lambda expressions cannot be converted to expression trees

Is there any workaround possible?

回答1:

C# can only convert lambda expression to Expression tree only if code can be represented by Expression Tree, if you notice, there is no equivalent of "async" keyword in Expressions in System.Linq.Expressions

So not only async, but anything in C# that has no equivalent expression in provided Expressions, C# can't convert it to Expression Tree.

Other examples are

  1. lock
  2. unsafe
  3. using


回答2:

The error is pretty self explanatory:

"Async lambda expressions cannot be converted to expression trees"

It's also documented in the Async/Await FAQ.

And for good reason, async-await is a compiler feature on top of the framework. Expressions are used to translate code to other commands (like SQL). These other languages probably don't have an async-await equivalent so enabling it via expressions doesn't seem worth it.

So no, I see no workaround.