Using Task Continuations

Task continuations allow you to chains of Tasks, which are performed in order, so when one Task in the chain finishes, the next one begins.

In a simple continuation, each Task in the chain is followed by one other Task, which can be useful but not deeply so. The true power of continuations arises with multitask and selective continuations. Multitask continuations schedule several Tasks when one finishes, or schedule one Task when several finish. They create the potential for fine-grained parallelism, where steps that were performed sequentially inside a larger Task body can now be performed in parallel. Selective continuations allow you to schedule Tasks based on the status of the previous Task in the chain, allowing you to create complex, yet natural, sets of Tasks to represent complex application states.

The following sections show you how to create and manage different types of continuations, building on what we learned in the previous chapter, as summarized in Table 4-1.

Table 4-1. Task Continuations

Problem Solution Listing

Table 4-1. Task Continuations

Create a simple continuation.

Use the Task.ContinueWith() method for each Task continuation.

4-1 and 4-2

Create selective continuations.

Use the Task.ContinueWith() method, and specify a value from the TaskContinuationOptions enumeration.

4-4

Create many-to-one and any-to-one continuations.

Use the TaskFactory.ContinueWhenAll() and Task.Factory.ContinueWhenAny() methods.

4-5 and 4-6

Canceling continuations.

Use a CancellationToken when using the ContinueWith() method and, optionally, the NotOnCanceled value from the TaskContinuationOptions enumeration.

4-7

Handle exceptions in task continuations.

Use selective continuations with the OnlyOnFaulted and NotOnFaulted values from the TaskContinuationOptions enumeration or propagate exceptions by handling and re-throwing them in continuations.

4-8 and 4-9

0 0

Post a comment