检查Action是否为异步Lambda [英] Check if Action is async lambda
问题描述
因为我可以将动作定义为
Since I can define an Action as
Action a = async () => { };
我能以某种方式确定(在运行时)动作a是否异步?
Can I somehow determine (at run time) whether the action a is async or not?
推荐答案
否-至少不明智. async
只是源代码注释,用于告诉C#编译器您确实需要异步函数/匿名函数.
No - at least not sensibly. async
is just a source code annotation to tell the C# compiler that you really want an asynchronous function/anonymous function.
您可以获取委托的MethodInfo
并检查其是否具有适当的属性.我个人不会-需要知道的是设计气味.特别是,请考虑一下,如果您将大部分代码从lambda表达式中重构为另一个方法,然后使用:
You could fetch the MethodInfo
for the delegate and check whether it has an appropriate attribute applied to it. I personally wouldn't though - the need to know is a design smell. In particular, consider what would happen if you refactored most of the code out of the lambda expression into another method, then used:
Action a = () => CallMethodAsync();
到那时,您没有拥有异步lambda,但是语义是相同的.为什么要让使用委托的任何代码表现不同?
At that point you don't have an async lambda, but the semantics would be the same. Why would you want any code using the delegate to behave differently?
此代码似乎有效,但我强烈建议不要使用它:
This code appears to work, but I would strongly recommend against it:
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);
}
}
这篇关于检查Action是否为异步Lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!