Concurrent collections

The .NET Core framework provides a variety of collections with which we can use LINQ queries. As a developer, there are far fewer options when looking for thread-safe collections. Without thread-safe collections, it can become difficult for developers when they have to perform multiple operations. In this case, we would meet the race condition that we have already discussed in Chapter 4Implementing Design Patterns - Basics Part 2. To overcome such situations, we need to use the lock statement, as we have used in the previous section. For example, we can write a code of a simplified implementation of the lock statement—refer to the following code snippet, where we have used the lock statement and collection class, Dictionary:

public bool UpdateQuantity(string name, int quantity)
{
lock (_lock)
{
_books[name].Quantity += quantity;
}

return true;
}

The preceding code is from InventoryContext; in this code, we are blocking other threads from locking the operation in which we are trying to update the quantity.

The main drawback of the Dictionary collection class is that it is not thread-safe. We have to use this in the lock statement while we're using Dictionary with multiple threads. To make our code thread-safe, we can use the ConcurrentDictionary collection class.

ConcurrentDictionary is a thread-safe collection class and stores key-value pairs. This class has the implementation for the lock statement and provides a thread-safe class. Consider the following code:

private readonly IDictionary<string, Book> _books;
protected InventoryContext()
{
_books = new ConcurrentDictionary<string, Book>();
}

The preceding code snippet is from the InventoryContext class of our FlixOne console application. In this code, we have the _books field, and it is initialized as a ConcurrentDictionary collection class.

As we are using the UpdateQuantity() method of the InventoryContext class in multithreads, there is a chance that one thread adds the quantity, while the other thread resets the quantity to its initial level. This happens because our object is from a single collection, and any changes to the collection in one thread are not visible to the other threads. All threads are referencing the original unmodified collection, and, in simple terms, our method is not thread-safe, unless we use the lock statement or the ConcurretDictionary collection class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.183.150