Using thread-safe collections
The generic collections we have seen so far are not thread-safe. This means that when they're used in multithreading scenarios, you need to protect access to these collections with external locks, which in many cases can degrade performance. .NET offers several thread-safe collections that use efficient locking and lock-free synchronization mechanisms to achieve thread-safety. These collections are provided in the System.Collections.Concurrent
namespace and should be used in scenarios where more than one thread is accessing a collection concurrently. However, the actual benefit may be smaller or greater than a standard collection being protected with an external lock. A discussion about this is provided later in this section.
Information box
The topic of multithreading and asynchronous programming will be addressed in Chapter 12, Multithreading and Async Programming, where you will learn about threads and tasks, synchronization mechanisms, the...