Today I'm very happy to announce that we released the stable version of the Microsoft.Bcl.Immutable NuGet package. We also published the MSDN documentation on immutable collections.
Nine months ago, we shipped the first preview of immutable collections. This was one of the first BCL features that we decided to ship early and often by releasing out of band (that is, outside the core .NET Framework releases). This allowed us to have a public design discussion, which, in turn, gave us the ability to address your feedback in a faster and more direct way than ever before.
Many of you participated and commented on our blog posts. Immutable collections wouldn't be what it is now in this stable release if it weren't for the great feedback and discussion we had with you. Thanks to everybody who participated!
What are immutable collections?
Over time, the .NET Framework has added many features that made concurrent programming a lot easier. This started with the introduction of the thread pool, got a lot more powerful with the task-based model and the Task Parallel Library (TPL), and was improved even more by the addition of the async and await language keywords.
While creating and running concurrently is easier than ever, one of the fundamental problems still exists: mutable shared state. Reading from multiple threads is typically very easy, but once the state needs to be updated, it gets a lot harder, especially in designs that require locking.
An alternative to locking is making use of immutable state. Immutable data structures are guaranteed to never change and can thus be passed freely between different threads without worrying about stepping on somebody else's toes.
This design creates a new problem though: How do you manage changes in state without copying the entire state each time? This is especially tricky when collections are involved.
This is where immutable collections come in. We created the following immutable collections to make it a lot easier to create immutable data structures:
- ImmutableDictionary<TKey, TValue>
- ImmutableSortedDictionary<TKey, TValue>
Let's look at an example. You have built a billing system and you see that an immutable design will enable you to pass orders around without having to worry about data corruption when multiple threads are involved. For example, you could implement printing selected orders from a worker thread by passing a snapshot of them to the thread. This way you avoid blocking the UI, and allow the user to edit orders without affecting the snapshot passed to the worker thread.
Read more: MSDN