I have a Dictionary<object1, List<object2> (a abstractisation I made for my structure, which is a little more complex).
The lists inside the dictionary are initialized in a non-parallel context, but adding new elements to the list needs a thread safe method. Removing items will not occure (the dictionary object will be disposed at the end of transactions).
Also, the key-value pairs are added only at initialisation, so no keys are added or removed from the dictionary during work, only the values are updated.
I can’t use concurent collections, I’m stuck in an old .NET Framework.
At first I locked the whole dictionary with a ReadWriteSlimlock. Well, this was very bad performance wise. There are many adding operations happening and they just wait for another. Locking only each list is a far better solution, because at least I’m doing stuff in parallel for each key.
Also, the adding operation are not simple list.Add(object2), some other complex operations need to occur in the thread safe area at adding.
But I don’t know what is the best way to implement it:
lock(dictionary.Value)?- Using a dictionary of
ReadWriteSlimlock(one for each key)? - Any other better solution?
Another solution could be to implement you concurent
List<object>class.Something like:
and in dictionary have:
Why encapsulate and and not extend
List<object>, is causeAddmethod is not virtual, so the only way you can “override” it, is usingnewkeyword, which is guranteed to be called only if used on the exactly same type, which means if you cast list to the base, it won’t be called, so hole architecture will fail.By encapsulating, you give to the caller only one method, where you control everything.
Don’t know if this solution fits your needs, but hope it gives you some hints on how possibly manage stuff.