I have a scenario where I have to keep reference counted object for given key in the ConcurrentDictionary
, if reference count reaches 0
, I want to delete the key. This has to be thread safe hence I am planning to use the ConcurrentDictionary
.
Sample program as follows. In the concurrent dictionary, I have key and value , the value is KeyValuePair which holds my custom object and reference count.
ConcurrentDictionary<string, KeyValuePair<object, int>> ccd =
new ConcurrentDictionary<string, KeyValuePair<object, int>>();
// following code adds the key, if not exists with reference
// count for my custom object to 1
// if the key already exists it increments the reference count
var addOrUpdateValue = ccd.AddOrUpdate("mykey",
new KeyValuePair<object, int>(new object(), 1),
(k, pair) => new KeyValuePair<object, int>(pair.Key, pair.Value + 1));
Now I want a way to remove the key when the reference count reaches to 0. I was thinking , remove method on ConcurrentDictionary
which takes key and predicate , removes the key if the predicate return 'true'. Example.
ConcurrentDictionary.remove(TKey, Predicate<TValue> ).
There is no such method on ConcurrentDictionary
, question is how to do the same in thread safe way ?.