Book Image

Hands-On Parallel Programming with C# 8 and .NET Core 3

By : Shakti Tanwar
Book Image

Hands-On Parallel Programming with C# 8 and .NET Core 3

By: Shakti Tanwar

Overview of this book

In today’s world, every CPU has a multi-core processor. However, unless your application has implemented parallel programming, it will fail to utilize the hardware’s full processing capacity. This book will show you how to write modern software on the optimized and high-performing .NET Core 3 framework using C# 8. Hands-On Parallel Programming with C# 8 and .NET Core 3 covers how to build multithreaded, concurrent, and optimized applications that harness the power of multi-core processors. Once you’ve understood the fundamentals of threading and concurrency, you’ll gain insights into the data structure in .NET Core that supports parallelism. The book will then help you perform asynchronous programming in C# and diagnose and debug parallel code effectively. You’ll also get to grips with the new Kestrel server and understand the difference between the IIS and Kestrel operating models. Finally, you’ll learn best practices such as test-driven development, and run unit tests on your parallel code. By the end of the book, you’ll have developed a deep understanding of the core concepts of concurrency and asynchrony to create responsive applications that are not CPU-intensive.
Table of Contents (22 chapters)
Free Chapter
1
Section 1: Fundamentals of Threading, Multitasking, and Asynchrony
6
Section 2: Data Structures that Support Parallelism in .NET Core
10
Section 3: Asynchronous Programming Using C#
13
Section 4: Debugging, Diagnostics, and Unit Testing for Async Code
16
Section 5: Parallel Programming Feature Additions to .NET Core

Canceling PLINQ queries

We can cancel a PLINQ query using the CancellationTokenSource and CancellationToken classes. The cancellation token is passed to the PLINQ query using the WithCancellation clause and then we can call CancellationToken.Cancel to cancel the query operation. When a query is canceled, it throws OperationCancelledException.

This is done as follows:

  1. Create a cancellation token source:
CancellationTokenSource cs = new CancellationTokenSource();
Create a task that starts immediately and cancel the token after 4 seconds
Task cancellationTask = Task.Factory.StartNew(() =>
{
Thread.Sleep(4000);
cs.Cancel();
});
  1. Wrap the PLINQ query inside a try block:
try
{
var result = range.AsParallel()
.WithCancellation(cs.Token)
.Select(number => number)
.ToList...