13 Thread-safe collections

 

This chapter covers

  • Challenges with using regular collections in a multi-threaded program
  • Using concurrent collections
  • Using the BlockingCollection class
  • Asynchronous alternatives to BlockingCollection
  • Utilizing immutable collections, and special considerations when using them
  • Using frozen collections

The System.Collections.Generic namespace contains many useful collections for us to use, however, we can’t just use them in a multithreaded application because all those collections are not thread-safe. In this chapter we’ll look at the issues with the simplest way of making collections thread-safe - just putting a lock around any access to the collection. We’ll also look at the thread-safe alternatives provided by the .net library.

Specifically, we’ll look at the concurrent collections added in .net framework 4, discuss the immutable collections added in .net Core (which is the basis for .net 5 and later), and talk about the frozen collections added in .net 8. We’ll see how to use each type of collection and when it’s appropriate to use it. But first, let’s talk about why we can’t just use the regular collections.

13.1 The problems with using the regular collections

13.2 The concurrent collections

13.2.1 ConcurrentDictionary<TKey,TValue>

13.2.2 BlockingCollection<T>

13.2.3 Async alternatives for BlockingCollection

13.2.4 ConcurrentQueue<T> and ConcurrentStack<T>

13.2.5 ConcurrentBag<T>

13.2.6 When to use the concurrent collections

13.2.7 When to not use the concurrent collections

13.3 The immutable collections

13.3.1 How immutable collections work

13.3.2 How to use the immutable collections

13.3.3 ImmutableInterlocked

13.3.4 ImmutableDictionary<TKey,TValue>

13.3.5 ImmutableHashSet<T> and ImmutableSortedSet<T>

13.3.6 ImmutableList<T>

13.3.7 ImmutableQueue<T> and ImmutableStack<T>

13.3.8 ImmutableArray<T>

13.3.9 When to use the immutable collections

13.4 The frozen collections

13.4.1 When to use the frozen collections

13.5 Summary