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 9: Working with Concurrent Collections in .NET

This chapter will dive deeper into some of the concurrent collections in the System.Collections.Concurrent namespace. These specialized collections help to preserve data integrity when using concurrency and parallelism in your C# code. Each section of this chapter will provide practical examples of how to use a specific concurrent collection provided by .NET.

We have seen some basic use of parallel data structures in .NET. We have already covered the basics of each of the concurrent collections in the Introduction to concurrency section of Chapter 2. So, we will quickly jump into the examples of their use in this chapter and learn more about their application and inner workings.

In this chapter, we will do the following:

  • Using BlockingCollection
  • Using ConcurrentBag
  • Using ConcurrentDictionary
  • Using ConcurrentQueue
  • Using ConcurrentStack

By the end of this chapter, you will have a deeper understanding...

Technical requirements

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

  • Visual Studio 2022 version 17.0 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 run only on Windows.

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

Let’s get started by learning more about BlockingCollection<T> and walk through a sample project that leverages the collection.

Using BlockingCollection

BlockingCollection<T> is one of the most useful concurrent collections. As we saw in Chapter 7, BlockingCollection<T> was created to be an implementation of the producer/consumer pattern for .NET. Let’s review some of the specifics of this collection before creating a different kind of sample project.

BlockingCollection details

One of the major draws of BlockingCollection<T> for developers working with parallel code implementations is that it can be swapped to replace List<T> without too many additional modifications. You can use the Add() method for both. The difference with BlockingCollection<T> is that calling Add() to add an item will block the current thread if another read or write operation is in process. If you want to specify a timeout period on the operation, you can use TryAdd(). The TryAdd() method optionally supports both timeouts and cancellation tokens.

Removing items from BlockingCollection<T...

Using ConcurrentBag

The ConcurrentBag<T> is an unordered collection of objects that can be safely added, peeked at, or removed concurrently. Keep in mind that, as with all of the concurrent collections, the methods exposed by ConcurrentBag<T> are thread-safe, but any extension methods are not guaranteed to be safe. Always implement your own synchronization when leveraging them. To review a list of safe methods, you can review this Microsoft Docs page: https://docs.microsoft.com/dotnet/api/system.collections.concurrent.concurrentbag-1#methods.

We are going to create a sample application that simulates working with a pool of objects. This scenario can be useful if you have some processing that leverages a stateful object that is memory-intensive. You want to minimize the number of objects created but cannot reuse one until the previous iteration has finished using it and returned it to the pool.

In our example, we will use a mocked-up PDF processing class that is assumed...

Using ConcurrentDictionary

In this section, we will create a WinForms application to load United States Food and Drug Administration (FDA) drug data concurrently from two files. Once loaded to ConcurrentDictionary, we can perform fast lookups with a National Drug Code (NDC) value to fetch the name. The FDA drug data is freely available to download in several formats from the NDC directory: https://www.fda.gov/drugs/drug-approvals-and-databases/national-drug-code-directory. We will be working with tab-delimited text files. I have downloaded the product.txt file and moved about half of the records to a product2.txt file, duplicating the header row in the second file. You can get these files in the GitHub repository for the chapter at https://github.com/PacktPublishing/Parallel-Programming-and-Concurrency-with-C-sharp-10-and-.NET-6/tree/main/chapter09/FdaNdcDrugLookup:

  1. Start by creating a new WinForms project in Visual Studio targeting .NET 6. Name the project FdaNdcDrugLookup...

Using ConcurrentQueue

In this section, we will create a sample project that is a simplified version of a realistic scenario. We are going to create an order queuing system using ConcurrentQueue<T>. This application will be a console application that enqueues orders for two customers in parallel. We will create five orders for each customer, and to mix up the order of the queue, each customer queuing process will use a different Task.Delay between calls to Enqueue. The final output should show a mix of orders dequeued for the first customer and the second customer. Remember that ConcurrentQueue<T> employs first in, first out (FIFO) logic:

  1. Let’s start by opening Visual Studio and creating a .NET console application named ConcurrentOrderQueue.
  2. Add a new class to the project named Order:
    public class Order
    {
        public int Id { get; set; }
        public string? ItemName { get; set; }
        public int ItemQty...

Using ConcurrentStack

In this section, we are going to experiment with BlockingCollection<T> and ConcurrentStack<T>. In the first example in this chapter, we used BlockingCollection<T> to read the words that started with a specific letter from the book Ulysses. We are going to make a copy of that project and change the code that reads the lines of text to use ConcurrentStack<T> inside BlockingCollection<T>. This will make the lines output in reverse order because a stack uses last in, first out (LIFO) logic. Let’s get started!

  1. Make a copy of the ParallelExtras.BlockingCollection project from this chapter or modify the existing project if you prefer.
  2. Open MainWindow.xaml.cs and modify the LoadBookLinesFromFile method to pass a new ConcurrentStack<string> to the constructor of BlockingCollection<string>:
    private async Task<BlockingCollection<string>> 
        LoadBookLinesFromFile()
    {
      ...

Summary

In this chapter, we delved into five of the collections in the System.Collections.Concurrent namespace. We created five sample applications in the chapter to get some hands-on experience with each of the concurrent collection types available in .NET 6. Through a mix of WPF, WinForms, and .NET console application projects, we examined some real-world methods of leveraging these collections in your own applications.

In the next chapter, we will explore the rich set of tools provided by Visual Studio for multithreaded development and debugging. We will also discuss some techniques for analyzing and improving the performance of parallel .NET code.

Questions

  1. Which concurrent collection can implement different types of collections under the covers?
  2. What is the default internal collection type implemented by the collection in question 1?
  3. Which collection type is frequently used as an implementation of the producer/consumer pattern?
  4. Which concurrent collection contains key/value pairs?
  5. Which method is used to add values to ConcurrentQueue<T>?
  6. Which methods are used to add and get items in ConcurrentDictionary?
  7. Are extension methods used with the concurrent collections thread-safe?
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 €14.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