Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async/await restrictions

Tags:

c#

async-await

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>
like image 521
Ondrej Janacek Avatar asked Dec 05 '22 08:12

Ondrej Janacek


2 Answers

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.

like image 51
Stephen Cleary Avatar answered Dec 29 '22 17:12

Stephen Cleary


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.

like image 38
Reed Copsey Avatar answered Dec 29 '22 15:12

Reed Copsey