Since dataflow blocks are built on the Task
infrastructure of the TPL, cancellation is supported by obtaining CancellationToken
from CancellationTokenSource
.
In this recipe, we will create a dataflow pipeline to download the contents of a classic book and perform a word count, except this time, we will enable the blocks that form the pipeline to be cancelled.
Let's see how we can add cancellation to our dataflow blocks.
Start a new project using the Console Application project template and assign
CancelDataflow
as the Solution name.Next, go to the Solution Explorer, right-click on References, click on Manage NuGet Packages, and add a reference to the TPL Dataflow library.
Open up
Program.cs
and add the followingusing
directives to the top of yourProgram
class:using System; using System.Linq; using System.Threading.Tasks.Dataflow; using System.Net; using System.Threading;
In the
Main
method, create a newCancellationTokenSource
object.var cancellationSource...