如何判断C#方法是否通过反射异步/等待?

例如

class Foo { public async Task Bar() { await Task.Delay(500); } }

如果我们反思这个类和方法,我如何确定这是否是一个实际的异步/等待方法,而不是简单的一个方法来返回一个任务?

class Foo { public Task Bar() { return Task.Delay(500); } }
在我的代码副本中,async方法的MethodInfo在CustomAttributes属性中包含以下项:

>一个DebuggerStepThroughAttribute
>一个AsyncStateMachineAttribute

而普通方法的MethodInfo在其CustomAttributes属性中不包含任何项。

看起来像AsyncStateMachineAttribute should reliably be found on an async method and not on a standard one

编辑:其实这个页面甚至在下面的例子中呢!

As the following example shows, you can determine whether a method is marked with Async (Visual Basic) or async (C# Reference) modifier. In the example, IsAsyncMethod performs the following steps:

• Obtains a MethodInfo object for the method name by using Type.GetMethod.

• Obtains a Type object for the attribute by using GetType Operator (Visual Basic) or typeof (C# Reference).

• Obtains an attribute object for the method and attribute type by using MethodInfo.GetCustomAttribute. If GetCustomAttribute returns Nothing (Visual Basic) or null (C#), the method doesn’t contain the attribute.

private static bool IsAsyncMethod(Type classType, string methodName)
{
    // Obtain the method with the specified name.
    MethodInfo method = classType.GetMethod(methodName);

    Type attType = typeof(AsyncStateMachineAttribute);

    // Obtain the custom attribute for the method. 
    // The value returned contains the StateMachineType property. 
    // Null is returned if the attribute isn't present for the method. 
    var attrib = (AsyncStateMachineAttribute)method.GetCustomAttribute(attType);

    return (attrib != null);
}
http://stackoverflow.com/questions/20350397/how-can-i-tell-if-a-c-sharp-method-is-async-await-via-reflection

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:如何判断C#方法是否通过反射异步/等待?