C# Parallel Programming: Working with Concurrent Collections — Part V
In the last article, we check with BlockCollection class to work with collection in our multitasking applications. This time let’s see how to work with ConcurrentDictionary.
As with other classes, the ConcurrentDictionary can be found in System.Collections.Concurrent namespace. The code below presents a sample about how to handle “players” and their “scores” with ConcurrentDictionary:
First, a new collection called players, from the ConcurrentDictionary type was created. Next, four tasks were created to be called in a concurrent way and to handle the collection:
- createPlayerTask: adds a new player in the game. Every 2 seconds, a new player is added to the collection through the method ConcurrentDictionary.TryAdd.
- removePlayerTask: removes any player from the game. Every 2 seconds, a random player is removed from the collection through the method ConcurrentDictionary.TryRemove.
- updateScoreTask: updates all player’s scores. We get the player with ConcurrentDictionary.TryGetValue method and after 100 milliseconds, the player’s score is updated through ConcurrentDictionary.TryUpdate method.
- showScoreTask: iterates through the collection to present each player and its score.
Finally, we call all tasks from Task.WhenAll method. This method will run all tasks in different threads, creating a little concurrency that we want for the collection operations.
I hope that this can be helpful for you! HAPPY CODING!!
Ref.: