Chapter 8. Collections

Using the proper collections is essential in concurrent applications. I’m not talking about the standard collections like List<T>; I assume you already know about those. The purpose of this chapter is to introduce newer collections that are specifically intended for concurrent or asynchronous use.

Immutable collections are collection instances that can never change. At first glance, this sounds completely useless; but they’re actually very useful even in single-threaded, nonconcurrent applications. Read-only operations (such as enumeration) act directly on the immutable instance. Write operations (such as adding an item) return a new immutable instance instead of changing the existing instance. This is not as wasteful as it first sounds because most of the time immutable collections share most of their memory. Furthermore, immutable collections have the advantage of being implicitly safe to access from multiple threads; since they cannot change, they are threadsafe.

Tip

Immutable collections are in the Microsoft.Bcl.Immutable NuGet package.

At the time of this writing, immutable collections are new, but they should be considered for all new development unless you need a mutable instance. If you’re not familiar with immutable collections, I recommend that you start with Recipe 8.1, even if you don’t need a stack or queue, because I’ll cover several common patterns that all immutable collections follow.

If you need to construct an immutable collection with lots of ...

Get Concurrency in C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.