C# Parallel Programming: Working with Concurrent Collections — Part VI
How about creating our own concurrent collection with .NET? In this article let’s see how can we create a concurrent collection with the IProducerConsumerCollection interface.
The IProducerConsumerCollection interface contains methods that allow us to handle thread-safe collections. This interface can be found in System.Collections.Concurrent namespace.
The code below presents a simple approach how creating a thread-safe Queue with IProducerConsumerCollection. Note that to control the concurrency on Queue collection, the code uses the lock statement in the operations.
From the code above, four methods are part of IProducerConsumerCollection:
- CopyTo: copies elements from the collection to an existing array.
- ToArray: copies elements from the collection to a new array.
- TryTake: tries to take and remove an item from the collection.
- TryAdd: tries to add a new item to the collection.
The others methods in the code, belong to ICollection and IEnumerable interface, present in IProducerConsumerCollection.
Now that we have our thread-safe Queue (MySafeQueue), let’s see how to work with it. The code below simulates Orders that are being sent to a consumer:
There are two tasks in the code that will be run in different threads. The first one is the producerTask, which is responsible to create and add new Orders in the MySafeQueue collection.
The second task is the consumerTask. This task will take and remove Orders from the MySafeQueue collection and presents them to the user. Note that this task will check the collection when the CancellationToken does not to be canceled.
Finally, through method Task.WaitAll, all tasks will be run, and this will be completed after 2 seconds when the CancellationToken receives the signal to be canceled.
I hope that this can be helpful for you! HAPPY CODING!!
Ref.: