Retrieving a Task’s Result

Because tasks can return a value as the result of background computation, an obvious question is how to retrieve the result. This section examines one way, which leaves the Task<TResult>-based world of asynchrony and blocks until the result is available. Later in this chapter, we discuss how to schedule more work based on a task’s result, using the concept of continuations (see the “Continuations” section).

Here’s how to retrieve a task’s result: Just call the Result property. This causes the receiving thread to block until the result is available:

var task = new Task<int>(() => {    // Do lots of work here, computing int value "res".    return res;});// Do other useful work until you can't ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.