liveBook · Manning

Task.Wait

As explained in C# Concurrency: Asynchronous and multithreaded programming

A .NET Task method that synchronously waits for the task to complete and propagates unsuccessful completion as an exception.

Task.Wait synchronously blocks the current thread until a Task completes. It suits legacy synchronous code that must consume an API offering only a Task-based asynchronous method, but it is inefficient, can cause deadlocks, and should be a last resort. section 3.2.3

After completion, Task.Wait behaves as follows:

  • Returns immediately when the task completed successfully. section 3.2.4
  • Throws when the task was canceled or faulted; fault details are represented by AggregateException and its InnerExceptions collection. section 3.2.4
  • Allows status inspection through IsFaulted, IsCanceled, and IsCompletedSuccessfully before deciding how to handle the result. section 3.2.4

Synchronous consumption of an asynchronous file API

var readCompleted = File.ReadAllBytesAsync("example.bin"); readCompleted.Wait(); // use the completed data through the task's result section 3.2.3

var readCompleted = File.ReadAllBytesAsync("example.bin");
var bytes = readCompleted.Result;                           #1
// do something with bytes

Compare Task<T>.Result with Task.Wait when adapting asynchronous file reading to synchronous code. section 3.2.3

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains blocking, completion states, exceptions, AggregateException, and deadlock risk; defers detailed cancellation treatment.
Examples
Uses File.ReadAllBytesAsync with Result and demonstrates status inspection, Wait, and InnerExceptions handling.
What it assumes
Assumes synchronous code and Task-based asynchronous methods; teaches blocking and completion-state checks.
What you can do after
Apply it via Task.Wait to synchronously consume a Task and handle faulted or canceled completion.
How it connects
Connects Task.Wait with Task<T>.Result, task completion status, async/await, cancellation, and AggregateException.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C# Concurrency: Asynchronous and multithreaded programming. The section links point to the parts of the book it draws on.