e.g.
class Foo { public async Task Bar() { await Task.Delay(500); } }
如果我们反思这个类和方法,我如何确定这是否是一个实际的 async/await 方法,而不仅仅是一个恰好返回任务的方法?
class Foo { public Task Bar() { return Task.Delay(500); } }
在我的代码副本中,MethodInfo
为了async
方法中包含以下项目CustomAttributes
财产:
- a
DebuggerStepThroughAttribute
- a
AsyncStateMachineAttribute
而MethodInfo
对于正常方法包含no其内的项目CustomAttributes
财产。
似乎是AsyncStateMachineAttribute
should reliably被发现于async方法而不是标准方法 http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.asyncstatemachineattribute.aspx.
编辑:事实上,该页面的示例中甚至有以下内容!
如以下示例所示,您可以确定方法是用 Async (Visual Basic) 还是 async(C# 参考)修饰符标记。在示例中,IsAsyncMethod 执行以下步骤:
-
使用 Type.GetMethod 获取方法名称的 MethodInfo 对象。
-
使用 GetType 运算符 (Visual Basic) 或 typeof(C# 参考)获取属性的 Type 对象。
-
使用 MethodInfo.GetCustomAttribute 获取方法和属性类型的属性对象。如果 GetCustomAttribute 返回 Nothing (Visual Basic) 或 null (C#),则该方法不包含该属性。
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)