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

2 comments:

Anonymous said...

Hello
phentermine cost
5 at one of reputable online pharmacies.
[url=http://www.ccmag2.com/]order phentermine[/url]
Phentermine goes to work releasing epinephrine and adrenaline causing you to lose fatty calories.
http://www.ccmag2.com/ - phentermine weight loss
After undergoing a physical at your doctors he may decide that you are qualified to sample Phentermine.

Anonymous said...

Hello all
Top Online Casino
Games such as roulette, slots, blackjack, and others seem to be online casino favorites.
[url=http://www.coronasoft.com/]Casino Game Download[/url]
Playing for money on online casino
Start playing casino games right now! You can play just for fun or for real money! Free welcome bonuses are guaranteed!
Throughout the past centuries mankind has had a love for gambling.
http://www.coronasoft.com/ - Casino Bonus
Since then there have grown to be thousands of these online casinos.