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 2: Evolution of Multithreaded Programming in .NET

As .NET and C# have evolved over the last 20 years, new and innovative approaches to multithreaded programming have been introduced. C# has added new language features to support asynchronous programming, and .NET Framework and .NET Core have added new types to support the languages. The most impactful improvements were introduced with C# 5 and .NET Framework 4.0 when Microsoft added the Task Parallel Library (TPL), thread-safe collections, and the async and await keywords.

This chapter will introduce concepts and features that will be explored in greater depth in subsequent chapters. These concepts include the .NET thread pool, asynchronous programming with async and await, concurrent collections, and parallelism. We will start by discovering when and why threading features were added to .NET and C#. Then, we will create some practical examples of how to use the new concepts. Finally, we will wrap up the chapter by discussing...

Technical requirements

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

  • Visual Studio 2022 version 17.0 or later.
  • .NET 6.
  • To use the WorkingWithTimers project, you will need to install the Visual Studio workload for .NET desktop development.

While these are recommended, if you have .NET 6 installed, you can use your preferred editor. For example, Visual Studio 2022 for Mac on macOS 10.13 or later, JetBrains Rider, or Visual Studio Code will work just as well.

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/chapter02.

Let’s start the chapter with a .NET and C# history lesson.

.NET threading through the years

Working with threads in .NET and C# has undergone much evolution since .NET Framework 1.0 and C# 1.0 were introduced in 2002. Most of the concepts discussed in Chapter 1, regarding the System.Threading.Thread objects have been available since those early days of .NET. While the Thread object is still available in .NET 6 and can be useful for simple scenarios, there are more elegant and modern solutions that are available today.

This section will highlight when the most impactful parallelism and concurrency features were added. We will begin by skipping ahead 8 years to 2010.

C# 4 and .NET Framework 4.0

In 2010, Microsoft released Visual Studio 2010 alongside C# 4 and .NET Framework 4.0. While some earlier language and framework features such as generics, lambda expressions, and anonymous methods would help facilitate later threading features, these 2010 releases were the most significant for threading since 2002. .NET Framework included the...

Beyond threading basics

Before we introduce parallel programming, concurrency, and async programming with .NET and C#, we have a few more threading concepts to cover. The most important of these is the .NET managed thread pool, which is used by awaited method calls that execute asynchronously in C#.

Managed thread pool

The ThreadPool class in the System.Threading namespace has been part of .NET since the beginning. It provides developers with a pool of worker threads that they can leverage to perform tasks in the background. In fact, that is one of the key characteristics of thread pool threads. They are background threads that run at the default priority. When one of these threads completes its task, it is returned to the pool of available threads to await its next task. You can queue as many tasks to the thread pool as the available memory will support, but the number of active threads is limited by the number that the operating system can allocate to your application, based...

Introduction to parallelism

While exploring the history of threading in C# and .NET, we learned that parallelism was introduced to developers in .NET Framework 4.0. In this section, the aspects that will be explored are exposed in the TPL through the System.Threading.Tasks.Parallel class. In addition, we will cover some of the basics of PLINQ through examples. These data parallelism concepts will be covered in greater detail with real-world examples in Chapter 6, Chapter 7, and Chapter 8.

At a high level, parallelism is the concept of executing multiple tasks in parallel. These tasks could be related to one another, but this is not a requirement. In fact, related tasks running in parallel run a greater risk of encountering synchronization issues or blocking one another. For example, if your application loads order data from an orders service and user preferences and application state from an Azure blob store, these two processes can be run in parallel without having to worry about...

Introduction to concurrency

So, what is concurrency and how does it relate to parallelism in the context of C# and .NET? The terms are frequently used interchangeably, and if you think about it, they do have similar meanings. When multiple threads are executing in parallel, they are running concurrently. In this book, we will use the term concurrency when discussing patterns to follow when designing for managed threading. Additionally, we will discuss concurrency in the context of the concurrent collections that were introduced to .NET developers in .NET Framework 4.0. Let’s start by learning about the concurrent collections in the System.Collections.Concurrent namespace.

.NET has several collections that have been created with thread safety built-in. These collections can all be found in the System.Collections.Concurrent namespace. In this section, we will introduce five of the collections. The remaining three are variations of Partitioner. These will be explored in Chapter...

Basics of async and await

When the TPL was introduced in .NET Framework 4.5, C# 5.0 also added language support for task-based asynchronous programming with the async and await keywords. This immediately became the default method of implementing asynchronous workflows in C# and .NET. Now, 10 years later, async/await and the TPL have become an integral part of building robust, scalable .NET applications. You might be wondering why it is so important to adopt async programming in your applications.

Understanding the async keyword

There are many reasons for writing async code. If you’re writing server-side code on a web server, using async allows the server to handle additional requests while your code is awaiting a long-running operation. On a client application, freeing the UI thread to perform other operations with async code allows your UI to remain responsive to users.

Another important reason to adopt async programming in .NET is that many third-party and open source...

Choosing the right path forward

Now that you have been introduced to some advanced managed threading concepts, parallel programming, concurrent collections, and the async/await paradigm, let’s discuss how they all fit together in the real world. Choosing the right path forward with multithreaded development in .NET will usually involve more than one of these concepts.

When working with .NET 6, you should usually choose to create async methods in your projects. The reasons discussed in this chapter are compelling. Asynchronous programming keeps both client and server applications responsive, and async is used extensively throughout .NET itself.

Some of the Parallel class operations can be leveraged when your code needs to process a set of items quickly and the underlying code doing the processing is thread-safe. This is one place where concurrent collections can be introduced. If any parallel or async operations are manipulating shared data, the data should be stored in...

Summary

In this chapter, we started by looking at a brief history of C#, .NET, and managed threading. We discussed how Microsoft has added features for asynchronous and parallel programming over the last 20 years. Next, we took a tour of parallel programming with .NET, concurrent collections, and asynchronous development with C#. Finally, we examined when you might choose each of these concepts for your own applications and why you will often choose more than one of them. You will be able to take what you learned in this chapter and start thinking about practical applications of managed threading in your day-to-day work.

In the next chapter, we will take what you have learned so far and discuss some of the best practices for the practical application of the concepts.

Questions

  1. Which class in .NET manages the thread pool threads available to your application?
  2. In which version of C# were the async and await keywords introduced?
  3. In which version of .NET was the TPL introduced?
  4. In which version of .NET Core was IAsyncEnumerable introduced?
  5. What type should every async method return?
  6. Which concurrent collection would you choose to replace Dictionary<TKey, TValue> in a multithreaded scenario?
  7. Which concurrent collection is frequently used with the producer/consumer design pattern in .NET?
  8. Which parallel feature in .NET features the AsParallel method?
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