Showing posts with label thread safe ictionary. Show all posts
Showing posts with label thread safe ictionary. Show all posts

Wednesday, May 9, 2007

Synchronized thread safe Dictionary

While working in a multi threaded environment i tried to work with a dictionary today. After reading some documentation on msdn i understood that the Dictionary class is not really a thread safe class and if we want to do that we need to make it thread safe we need to do it ourselves.
I understood the fact and tried to write a wrapper over this class and make a generic thread safe dictionary for using it in my application.
So what i did in this wrapper is i maintained a reference to the generic dictionary and implemented IDictionary interface. I plainly delegated the calls to the reference however made sure that each of the call acquires the lock over the object and hence i assumed that my dictionary is a thread safe dictionary.
However while discussing it with one of the colleagues i realize that still is not really a thread safe class. It can still cause problem when i am trying to use IEnumerator. Let's see how

when we loop through a dict with 3 elements with SynchronizedDictionary

foreach(KeyValue keyValue in dict) {...}

will perform like

lock

get enumerator

unlock

<--- another thread might modify as dict is not locked now

lock (assuming returned enumerator calls this[TKey key] for fetching items. else it won't be even locked!)

get first item

unlock

<--- another thread might modify as dict is not locked now

lock

get second item

unlock

<--- another thread might modify as dict is not locked now

lock

get third item

unlock


and hence there's a problem.
Any suggestions out there so resolve this problem.

~Abhishek