检查Action是否为异步lambda

因为我可以将Action定义为

Action a = async () => { }; 

我可以以某种方式确定(在运行时)动作是否异步?

不 – 至少不明智。 async只是一个源代码注释,告诉C#编译器你真的想要一个异步函数/匿名函数。

可以获取委托的MethodInfo并检查它是否已应用适当的属性。 我个人不会 – 需要知道的是设计气味。 特别是,考虑如果将lambda表达式中的大部分代码重构为另一个方法会发生什么,然后使用:

 Action a = () => CallMethodAsync(); 

那时你没有异步lambda,但语义也是一样的。 为什么您希望使用委托的任何代码表现不同?

编辑:此代码似乎工作,但我强烈建议反对它

 using System; using System.Runtime.CompilerServices; class Test { static void Main() { Console.WriteLine(IsThisAsync(() => {})); // False Console.WriteLine(IsThisAsync(async () => {})); // True } static bool IsThisAsync(Action action) { return action.Method.IsDefined(typeof(AsyncStateMachineAttribute), false); } } 

当然,你可以做到这一点。

 private static bool IsAsyncAppliedToDelegate(Delegate d) { return d.Method.GetCustomAttribute(typeof(AsyncStateMachineAttribute)) != null; }