What are other restrictions on using async
with a method signature and on using await
with an expression in these methods, if there are any? So far, I am aware that a method marked with async
can have only one of the following return types (maybe there are more?).
void
Task
Task<TResult>
I have an intro on my blog that you may find helpful.
await
only requires that it be passed an instance that is "awaitable" (matching a certain pattern, similar to how foreach
works). The most common awaitables are tasks, but there are others (e.g., Windows Store asynchronous operations).
async
must be used on any method that uses await
. async
methods must return Task
or Task<T>
, or, if you absolutely must, void
.
The async
modifier is only allowed on methods with a return type of void
, Task
, or Task<T>
. In general, it should only be used on methods which include an await
operator.
The await
operator can be used on any type t where (From C# language spec, 7.7.7):
t has an accessible instance or extension method called GetAwaiter with no parameters and no type parameters, and a return type A for which all of the following hold:
- A implements the interface System.Runtime.CompilerServices.INotifyCompletion
- A has an accessible, readable instance property IsCompleted of type bool
- A has an accessible instance method GetResult with no parameters and no type parameters
In practice, this typically means you can use await
on any Task
, Task<T>
, IAsyncOperation
, IAsyncOperation<T>
(from Windows Store API), and a few other select types in the framework.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With