By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,148 Members | 779 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,148 IT Pros & Developers. It's quick & easy.

Threads accessing a dictionary

P: n/a
Hi, I have a Dictionary<key, valuewhich is accessed by three threads.

One thread puts my value objects in the dictionary (occasionally), and
also updates the contents of existing value objects - by finding the
appropriate object via a key and updating the value (this updating
happens several times a second).

Another thread removes "dead" value objects from the dictionary (very

The third thread needs to loop through all the value objects in the
dictionary performing calculations based on their contents. This thread
needs to run maybe once every 10 seconds, do the calculations, and then
loop/wait again. I am not sure exactly how long these calculations will
take - but it will depend very much on the size of the dictionary
(maybe 1 or 2 seconds).

I foresee a problem with these threads accessing the same dictionary.
Especially the need for the third thread to loop over all the values
while it is possible these values could be being updated, or new values
could be being added or old values deleted.

Do I need to "lock" the entire dictionary while the third thread is
looping over the values? Is there a better way to avoid threading
Thanks for any comments,

Feb 20 '08 #1
Share this Question
Share on Google+
1 Reply

P: n/a
Do I need to "lock" the entire dictionary while the third thread is
looping over the values?
Just to clarify: you would need to lock from all 3 threads, not just
this one; locking only works if all the code plays by the same rules.

You might be able to do some things with reader/writer locks, but to
be honest I'd keep it simple and start with a simple exclusive lock
(aka Monitor, i.e. "lock(foo) {...}"). As Jon stated - if your
calculations are relatively slow, you can reduce contention by cloning
the data first then releasing the lock and doing the calculations on
the cloned data.

Of course; if your first thread is updating *properties* of the values
(rather than swapping the value entirely), then life gets even more
complex; in this case even a clone can't guarantee much, and you'd
need (to keep things simple) a lock covering the entire calculation

Feb 20 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.