Check if the action is asynchronous lambda

So how can I define an action as

Action a = async () => { }; 

Is it possible to somehow determine (at run time) whether action a is asynchronous or not?

+7
c # async-await
source share
2 answers

No - at least unreasonable. async is just an annotation for the source code to tell the C # compiler that you really want an asynchronous function / anonymous function.

You can get the MethodInfo for the delegate and check if it has the corresponding attribute applied to it. I personally would not want this - the need to know is the smell of design. In particular, consider what happens if you re-process most of the code from a lambda expression into another method, and then use:

 Action a = () => CallMethodAsync(); 

At this point, you do not have an asynchronous lambda, but the semantics will be the same. Why do you want any delegate code to behave differently?

EDIT: this code works, but I highly 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); } } 
+13
source share

Of course you can do it.

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

All Articles