I have the following code described in https://dotnetfiddle.net/GknA5Q from a production application. The dictionary
is used as a cache to keep the properties of an object. The REST API where this dictionary
is used has hundreds of object types, so the cache gets larger when the API finds more object types. The properties from the object is retrieved via reflection as you see in the code. The dictionary
gets populated when the API is started and hundreds of requests reach the API. Each request will have a object type whose properties are getting cached.
Although the REST API works, the code generates the following error now when the API starts in IIS. The line number that generates the error is 23 where TryGetValue
is being called.
Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.
I'm trying to reproduce the same error in a test application, so some solution can be applied. I don't want to remove the dictionary
which will add time for processing every model in every request that reaches the API. If this dictionary
cache is available, the properties can be retrieved from the cache instead of parsing through reflection.
How can I reproduce the above error?
The Dictionary<TKey, TValue>
class supports multiple readers but doesn't support multiple writers.
You can read the official documentation here: Dictionary<TKey,TValue> Class - Thread Safety
To test concurrency you may use the Parallel
class: Parallel Class
Parallel.For(0, 1000, i =>
{
// dictionary.Add(...)
});
A thread-safe implementation of IDictionary<TKey, TValue>
is the ConcurrentDictionary<TKey, TValue>
class:
ConcurrentDictionary<TKey,TValue> Class
You just need to replace Dictionary
in you code with ConcurrentDictionary
.