liveBook · Manning

Task<T>.Result

As explained in C# Concurrency: Asynchronous and multithreaded programming

A Task<T> property that provides the task's computed result and synchronously waits if the task has not completed, propagating cancellation or failure as an exception.

Task<T>.Result returns the value stored in a task. Reading it before completion synchronously blocks the current thread; reading it after completion returns immediately. A canceled or faulted task makes Result throw, so this property adapts asynchronous APIs to synchronous code at a significant cost. section 3.2.3 section 3.2.4

Use Result with these constraints:

  • Prefer reading Result only after IsCompleted is true or from a completion continuation; then the access is nonblocking. section 3.2.4 section 3.7
  • Avoid using Result as a general replacement for await: blocking is inefficient, removes asynchronous benefits, and can deadlock in some environments. section 3.2.3 section 3.7
  • Expect an AggregateException for faulted tasks and account separately for cancellation. section 3.2.4

Adapting an asynchronous file read

Start File.ReadAllBytesAsync("example.bin"), then read its Result property when synchronous code must obtain the byte array. This blocks until the read completes and propagates cancellation or failure. section 3.2.3

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

Shows the minimal synchronous bridge from File.ReadAllBytesAsync to the completed byte array. section 3.2.3

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains blocking, completion checks, exceptions, cancellation, and deadlock risk, but defers broader cancellation treatment.
Examples
Demonstrates synchronously obtaining bytes from File.ReadAllBytesAsync and reading intermediate values inside continuations.
What it assumes
Assumes basic Task<T> and completion knowledge while teaching how Result synchronously obtains a future value.
What you can do after
Operate synchronous code over Task<T> values while recognizing blocking, deadlock, cancellation, and AggregateException risks.
How it connects
Connects Task<T>.Result with Task, Wait, IsCompleted, Status, ContinueWith, 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.