Continuations

One advantage of using tasks is their better composition compared to lower-level constructs such as threads. As mentioned at the beginning of the “Task Parallelism” section, earlier in this chapter, tasks can produce a result of some type. Taking some further action based on the result (which also could be an error or even a cancellation) is a common thing to do. This is where continuations come in.

The Basic Concept

Although they sound scary, continuations are really simple constructs. Before going into the specifics of their use in conjunction with tasks, let’s explore them from a conceptual point of view. Consider the following piece of imperative sequential synchronous code:

int c = Add(a, b);Console.WriteLine(c);

This piece ...

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.