Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a C# method is async/await via reflection?

e.g.

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

If we are reflecting over this class and method, how can I determine if this is an actual async/await method rather than simply a method that happens to return a Task?

class Foo { public Task Bar() { return Task.Delay(500); } } 
like image 410
Isaac Abraham Avatar asked Dec 03 '13 11:12

Isaac Abraham


People also ask

Can a blown fuse cause AC not to work?

While this prevents serious trouble such as electrical fires, it also means that a single blown fuse can cause the entire air conditioner to stop working. Some of the most common causes of AC failure are rooted in electronics.

How do you test if your AC is working?

First, locate the closest supply air duct to your indoor AC unit. Then use a thermometer, even a refrigerator thermometer will work, and tape it just inside. Let your Air Conditioning run for about ten minutes then check and record the temperature.


1 Answers

In my copy of your code, the MethodInfo for the async method contains the following items in the CustomAttributes property:

  • a DebuggerStepThroughAttribute
  • a AsyncStateMachineAttribute

whereas the MethodInfo for the normal method contains no items in its CustomAttributes property.

It seems like the AsyncStateMachineAttribute should reliably be found on an async method and not on a standard one.

Edit: In fact, that page even has the following in the examples!

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); } 
like image 158
Rawling Avatar answered Sep 26 '22 23:09

Rawling