Await

The await keyword marks a point where the method cannot continue until the awaited async operation is complete.

  • It suspends this method and yields control back to the caller until then.
  • It signs up the rest of the method as a continuation.
  • It does not run on its own thread (unless called via Task.Run()).

Example

async Task<int> GetTaskOfResultAsync() {
	int hours = 0;
	await Task.Delay(0);
	return hours;
}

// This calls the async method:
Task<int> returnedTaskTResult = GetTaskOfResultAsync();
// This awaits the Task that the method returns and "unwraps" the int it holds:
int intResult = await returnedTaskTResult;

Awaiting Task.Run or Task/Task<T>

  • For I/O-bound code, await an operation that returns a Task or Task<T> inside an async method.
  • For CPU-bound code, await an operation that is started on a background thread with Task.Run.

TODO:

Await Decision Table

The Task.Wait* methods are synchronous, not asynchronous.

GoalUse thisNot this
Retrieve the result of a background TaskawaitTask.Wait or Task.Result
Waiting for any task to completeawait Task.WhenAnyTask.WaitAny
Waiting for all tasks to completeawait Task.WhenAllTask.WaitAll
Waiting for a period of timeawait Task.DelayThread.Sleep

Async Code & LINQ

Use caution. LINQ uses deferred (lazy) execution, so async calls won’t happen immediately (unless iteration is forced via .ToList() or .ToArray())