Linking blocks to create a pipeline
suggest changevar httpClient = new HttpClient();
// Create a block that accepts a URI and returns its contents as a string
var downloaderBlock = new TransformBlock<string, string>(
async uri => await httpClient.GetStringAsync(uri));
// Create a block that accepts the content and prints it to the console
var printerBlock = new ActionBlock<string>(
contents => Console.WriteLine(contents));
// Make the downloaderBlock complete the printerBlock when it has completed.
var dataflowLinkOptions = new DataflowLinkOptions {PropagateCompletion = true};
// Link the blocks to create a pipeline
downloaderBlock.LinkTo(printerBlock, dataflowLinkOptions);
// Post urls to the first block which will pass their contents to the second one.
downloaderBlock.Post("http://youtube.com");
downloaderBlock.Post("http://github.com");
downloaderBlock.Post("http://twitter.com");
downloaderBlock.Complete(); // Completion will propagate to printerBlock
await printerBlock.Completion; // Only need to wait for the last block in the pipeline
These types ship in the TPL Dataflow NuGet package. They are not in the .NET Framework base class library. The await must be inside an async method.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents