Reader small image

You're reading from  Parallel Programming and Concurrency with C# 10 and .NET 6

Product typeBook
Published inAug 2022
PublisherPackt
ISBN-139781803243672
Edition1st Edition
Right arrow
Author (1)
Alvin Ashcraft
Alvin Ashcraft
author image
Alvin Ashcraft

Alvin Ashcraft is a software engineer and developer community champion with over 25 years of experience in software development. Working primarily with Microsoft Windows, web, and cloud technologies, his career has focused primarily on the healthcare industry. He has been awarded as a Microsoft MVP 11 times, most recently as a Windows Dev MVP. Alvin works in the Philadelphia area for Allscripts, a global healthcare software company, as a principal software engineer. He is also a board member of the TechBash Foundation, where he helps organize the annual TechBash developer conference. He has previously worked for companies such as Oracle, Genzeon, CSC, and ITG Pathfinders. Originally from the Allentown, PA area, Alvin currently resides in West Grove, PA with his wife and three daughters.
Read more about Alvin Ashcraft

Right arrow

Chapter 11: Canceling Asynchronous Work

In the previous chapters, we’ve looked at a few examples of how to cancel threads and tasks. This chapter will explore more of the methods available to cancel concurrent and parallel work with C# and .NET. The methods in this chapter will provide alternative ways to cancel background operations using callbacks, polling, and wait handles. You will gain a deeper understanding of how to safely cancel asynchronous work with a variety of methods using some practical scenarios.

In this chapter, you will learn about the following topics:

  • Canceling managed threads
  • Canceling parallel work
  • Discovering patterns for thread cancellation
  • Handling multiple cancelation sources

By the end of this chapter, you will understand how to cancel different types of asynchronous and parallel tasks.

Technical requirements

To follow along with the examples in this chapter, the following software is recommended for Windows developers:

  • Visual Studio 2022 version 17.2 or later.
  • .NET 6.
  • To complete any WinForms or WPF samples, you will need to install the .NET desktop development workload for Visual Studio. These projects will only run on Windows.

All the code examples for this chapter can be found on GitHub at https://github.com/PacktPublishing/Parallel-Programming-and-Concurrency-with-C-sharp-10-and-.NET-6/tree/main/chapter11.

Canceling managed threads

Canceling asynchronous work in .NET is based on the use of a cancellation token. A token is a simple object that is used to signal that a cancellation request has been made to another thread. The CancellationTokenSource object manages these requests and contains a token. If you want to cancel several operations with the same trigger, the same token should be provided to all of the threads to be canceled.

A CancellationTokenSource instance has a Token property to access the CancellationToken property and pass it to one or more asynchronous operations. The request to cancel can only be made from the CancellationTokenSource object. The CancellationToken property provided to the other operations receives the signal to cancel but cannot initiate a cancellation.

CancellationTokenSource implements the IDisposable interface, so be sure to call Dispose when you are freeing your managed resources. A using statement or block to automatically dispose of the token...

Canceling parallel work

In this section, we will work with some examples of canceling parallel operations. There are a few operations that fall into this realm. There are static parallel operations that are part of the System.Threading.Tasks.Parallel class and there are PLINQ operations. Both of these types use a CancellationToken property, as we used in our managed threading example in the previous section. However, handling the cancellation request is slightly different. Let’s look at an example to understand the differences.

Canceling a parallel loop

In this section, we will create a sample that illustrates how to cancel a Parallel.For loop. The same method of cancellation is leveraged for the Parallel.ForEach method. Perform the following steps:

  1. Open the CancelThreadsConsoleApp project from the previous section.
  2. In the ManagedThreadsExample class, create a new ProcessTextParallel method with the following implementation:
    public static void ProcessTextParallel...

Discovering patterns for thread cancellation

There are different methods of listening for cancellation requests from a thread or task. So far, we have seen examples of managing these requests by either handling the OperationCanceledException type or checking the value of IsCancellationRequested. The pattern of checking IsCancellationRequested, usually inside a loop, is called polling. First, we will see another example of this pattern. The second pattern we will examine is receiving the notification by registering a callback method. The final pattern that we will cover in this section is listening to cancellation requests with wait handles using ManualResetEvent or ManualResetEventSlim.

Let’s start by trying another example of handling a cancellation request by polling.

Canceling with polling

In this section, we will create another example that uses polling to cancel a background task. The previous example of polling was running in a background thread on the ThreadPool...

Handling multiple cancellation sources

Background tasks can leverage CancellationTokenSource to receive cancellation requests from as many sources as necessary. The static CancellationTokenSource.CreateLinkedTokenSource method accepts an array of CancellationToken objects to create a new CancellationTokenSource object that will notify us of cancellation if any of the source tokens receives a request to cancel.

Let’s look at a quick example of how to implement this in our CancellationPatterns project:

  1. First, open the PollingExample class. We are going to create an overload of the CancelWithPolling method that accepts a CancellationTokenSource parameter. The two overloads of CancelWithPolling will look like this:
    public static void CancelWithPolling()
    {
        using CancellationTokenSource tokenSource = new();
        CancelWithPolling(tokenSource);
    }
    public static void CancelWithPolling
        (CancellationTokenSource...

Summary

In this chapter, we learned a number of new ways to cancel background threads and tasks. It is important to provide your users with a method of canceling long-running tasks or automatically canceling them when users or the operating system closes or suspends your application.

After working through the examples in this chapter, you now understand how to use polling, callbacks, and wait handles to cooperatively cancel background tasks. Additionally, you learned how to handle cancellation requests from more than one source.

In the next chapter, we will look at how .NET developers can unit test code that employs multithreaded constructs.

Questions

  1. Which property of a CancellationToken object indicates whether a cancellation request has been made?
  2. Which data type provides a CancellationToken object?
  3. What exception type is thrown when ThrowIfCancellationRequested is invoked?
  4. What cancellation pattern is used by the WebClient object in .NET?
  5. Which .NET type can pause or resume operations with a CancellationToken object?
  6. Which reset event is used to pause processing?
  7. Which static method in CancellationTokenSource can combine multiple CancellationToken objects into a single source?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Parallel Programming and Concurrency with C# 10 and .NET 6
Published in: Aug 2022Publisher: PacktISBN-13: 9781803243672
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Alvin Ashcraft

Alvin Ashcraft is a software engineer and developer community champion with over 25 years of experience in software development. Working primarily with Microsoft Windows, web, and cloud technologies, his career has focused primarily on the healthcare industry. He has been awarded as a Microsoft MVP 11 times, most recently as a Windows Dev MVP. Alvin works in the Philadelphia area for Allscripts, a global healthcare software company, as a principal software engineer. He is also a board member of the TechBash Foundation, where he helps organize the annual TechBash developer conference. He has previously worked for companies such as Oracle, Genzeon, CSC, and ITG Pathfinders. Originally from the Allentown, PA area, Alvin currently resides in West Grove, PA with his wife and three daughters.
Read more about Alvin Ashcraft