Table Of ContentParallel Programming and
Concurrency with C# 10 and .NET 6
A modern approach to building faster, more responsive, and
asynchronous .NET applications using C#
Alvin Ashcraft
BIRMINGHAM—MUMBAI
Parallel Programming and Concurrency with C# 10
and .NET 6
Copyright © 2022 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted
in any form or by any means, without the prior written permission of the publisher, except in the case
of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information
presented. However, the information contained in this book is sold without warranty, either express
or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable
for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and
products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot
guarantee the accuracy of this information.
Associate Group Product Manager: Gebin George
Publishing Product Manager: Sathyanarayanan Ellapulli
Senior Editor: Ruvika Rao
Content Development Editor: Yashi Gupta
Technical Editor: Maran Fernandes
Copy Editor: Safis Editing
Project Coordinator: Manisha Singh
Proofreader: Safis Editing
Indexer: Hemangini Bari
Production Designer: Roshan Kawale
Marketing Coordinator: Sonakshi Bubbar
First published: August 2022
Production reference: 1120822
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80324-367-2
www.packt.com
To my wife, Stelene, for supporting me through the process of writing a second
book and for helping me become my best self in our journey together. To my
three daughters, for working harder and smarter than I did at their ages and
for their patience during my writing process.
– Alvin Ashcraft
Co n t r i b u t o r s
About the author
Alvin Ashcraft is a writer, software engineer, and developer community champion with over 27 years
of experience in software and content development. He has worked with Microsoft Windows, web,
and cloud technologies since 1995 and has been awarded as a Microsoft MVP 13 times.
Alvin works remotely in the Philadelphia area for Microsoft as a content developer on Microsoft Learn
for the Windows developer documentation team. He also helps organize the TechBash developer
conference in the Northeast US. He has previously worked for companies such as Oracle, Genzeon,
and Allscripts. Originally from the Allentown, PA, area, Alvin currently resides in West Grove, PA,
with his wife and daughters.
I want to thank the people who have been close to me and supported me,
especially my parents and my wife, Stelene’s, parents.
About the reviewers
Ricardo Peres is a Portuguese developer, blogger, and book author and is currently a team leader at
Dixons Carphone. He has over 20 years of experience in software development and his interests include
distributed systems, architectures, design patterns, and .NET development. He won the Microsoft
MVP award in 2015 and held this title up to 2020.
He also authored Entity Framework Core Cookbook – Second Edition and Mastering ASP.NET Core 2.0
and was a technical reviewer for Learning NHibernate 4 for Packt. He also contributed to Syncfusion’s
Succinctly collection, with titles on .NET development. Ricardo maintains a blog—Development With
A Dot—where he writes about technical issues. You can keep up with him on Twitter at @rjperes75.
Joseph Guadagno is a senior director of engineering at Rocket Mortgage, the US’s largest mortgage
lender, based in Detroit, Michigan. He has been writing software for over 30 years and has been
an active member of the .NET community, serving as a Microsoft MVP in .NET, for more than 10
years. He has spoken throughout the United States and at international events on topics including
Microsoft .NET, Microsoft Azure, and SQL. You can see the complete list of events he has spoken at
at https://www.josephguadagno.net/presentations.
When not sitting at a computer, Joe loves to hang out with his family and play games. You can connect
with Joe on Twitter at @jguadagno, on Facebook at JosephGuadagnoNet, and on his blog at
https://www.josephguadagno.net.
Table of Contents
Preface
Part 1: Introduction to Threading in .NET
1
Managed Threading Concepts
Technical requirements 4 Handling threading exceptions 13
.NET threading basics 4 Synchronizing data across threads 14
Threads and processes 4 Synchronizing code regions 14
When should we use multithreading in .NET? 5 Manual synchronization 16
Background threads 5
Scheduling and canceling work 18
What is managed threading? 8
Scheduling managed threads 18
Creating and destroying threads 9 Canceling managed threads 21
Creating managed threads 9
Summary 25
Pausing thread execution 11
Questions 25
Destroying managed threads 13
2
Evolution of Multithreaded Programming in .NET
Technical requirements 28 C# 10 and .NET 6 31
.NET threading through the years 28 Beyond threading basics 31
C# 4 and .NET Framework 4.0 28 Managed thread pool 32
C# 5 and 6 and .NET Framework 4.5.x 29 Threading and timers 33
C# 7.x and .NET Core 2.0 29
Introduction to parallelism 37
C# 8 and .NET Core 3.0 30
Using Parallel.Invoke 38
viii Table of Contents
Using Parallel.ForEach 40 ConcurrentDictionary<TKey, TValue> 47
Basics of Parallel LINQ 41
Basics of async and await 47
Introduction to concurrency 43 Understanding the async keyword 47
ConcurrentBag<T> 44 Writing an async method 48
ConcurrentQueue<T> 45
Choosing the right path forward 50
ConcurrentStack<T> 45
Summary 51
BlockingCollection<T> 46
Questions 51
3
Best Practices for Managed Threading
Technical requirements 53 Mitigating deadlocks 61
Handling static objects 54 Avoiding race conditions 63
Static data and constructors 54 Threading limits and other
Controlling shared access to static objects 56 recommendations 66
Managing deadlocks and race Summary 69
conditions 60 Questions 69
4
User Interface Responsiveness and Threading
Technical requirements 71 Updating the UI thread without
Leveraging background threads 72 exceptions 85
Summary 88
Which threads are background threads? 72
Using async, await, tasks, and WhenAll 73 Questions 88
Using the thread pool 82
Table of Contents ix
Part 2: Parallel Programming and Concurrency
with C#
5
Asynchronous Programming with C#
Technical requirements 92 Interop with synchronous code 106
More about asynchronous Executing async from synchronous methods 107
programming in .NET 92 Executing synchronous code as async 110
I/O-bound operations 92 Working with multiple background
CPU-bound operations 94 tasks 113
Nested async methods 97
Asynchronous programming best
Working with Task objects 102 practices 114
Exploring Task methods 103 Summary 115
Exploring Task properties 105 Questions 116
6
Parallel Programming Concepts
Technical requirements 117 Cancel a Parallel.ForEachAsync loop 128
Getting started with the TPL 118 Relationships between parallel tasks 131
I/O-bound operations 118 Under the covers of Parallel.Invoke 131
CPU-bound operations 119 Understanding parallel child tasks 132
Parallel loops in .NET 119 Common pitfalls with parallelism 137
Basic Parallel.For loops 119 Parallelism is not guaranteed 137
Parallel loops with thread-local variables 124 Parallel loops are not always faster 137
Simple Parallel.ForEach loops 126