Chapter 9. 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 isn’t 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 System.Collections.Immutable NuGet package.

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

There are special ways to more efficiently construct an immutable collection with ...

Get Concurrency in C# Cookbook, 2nd Edition 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.