Async lambda to Expression <Func <Task >>

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

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

How can I do the same with asynchronous lambda? I 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 a workaround possible?

+5
source share
2 answers

C # can only convert a lambda expression to an expression tree only if the code can be represented by an expression tree, if you notice that there is no "async" expression in the expressions of System.Linq.Expressions

Thus, not only async, but also anything in C # that does not have an equivalent expression in the provided expressions, C # cannot convert it to an Expression Tree.

Other examples are

  • Castle
  • unsafe
  • using buttons
+6
source

The error is pretty clear:

"Asynchronous lambda expressions cannot be converted to expression trees"

It is also documented in Async / Await Frequently Asked Questions .

And for good reason, async-await is a compiler function on top of the framework. Expressions are used to translate code to other commands (for example, SQL). These other languages ​​probably don't have the equivalent of async-await , so including it with expressions is not worth it.

No, I do not see a workaround.

+4
source

All Articles