I have a method that returns an object that can be any type. If the object instance is awaitable, I need to await it and get its result. I know I can check for the object to be a Task/ValueTask or their generic counterparts, but those are not the only things that are awaitable.
object result = GetResult();
object actualResult = result is Awaitable awaitable // "Awaitable" isn't a thing
? await awaitable
: result;
The C# language specification says that an expression t
is awaitable if one of the following holds:
t
is of compile-time typedynamic
t
has an accessible instance or extension method calledGetAwaiter
with no parameters and no type parameters, and a return typeA
for which all of the following hold:- A implements the interface
System.Runtime.CompilerServices.INotifyCompletion
- A has an accessible, readable instance property
IsCompleted
of typebool
- A has an accessible instance method
GetResult
with no parameters and no type parameters
- A implements the interface
What is the best way to determine whether an object is awaitable or not?
Other answers to questions similar to this suggest that it's not possible. That can't be true since the compiler knows what is and isn't awaitable. I'm looking for some framework-level methods to determine an object's awaitability.
Another practical example of this takes place in ASP.NET MVC Controllers. Controller methods can return IActionResult
or Task<IActionResult>
and the code that executes these actions knows whether or not to await the result objects. I can't find the location in the source code where this check happens though.
Task
return type's doing, not someis Awaitable
check?GetAwaiter().GetResult()
. Is that what you want?