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.