473,405 Members | 2,167 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

threading: acessing a Dictionary<TKey,TValue> with foreach

Hello I am acessing a Dictionary<TKey,TValuefrom multiple threads and
often in a foreach loop. While I am within one of the foreach loops the
other threads must not modify the collection itself since that would
cause an exception in the foreach loop "foreach can not continue
because the colelction was modifed". Now what is the least expensive
and threadsafe way to make sure that no other threads modifies that
collection. Since one of the threads will do a foreach over the
collection once every 2seconds I fear doing a complete lock
(mycollection){} on the collection. Sinc I was told that this is
expensive. As far as I can see, all I need is a lock for writing, other
threads still may READ the data of the collection. Or are there any
sideeffects I might not be aware of yet? What is the best practise
here? How do I aquire a writeonly lock (in case this is the best
solution) ?

Aug 9 '06 #1
7 6121
bonk wrote:
Hello I am acessing a Dictionary<TKey,TValuefrom multiple threads and
often in a foreach loop. While I am within one of the foreach loops the
other threads must not modify the collection itself since that would
cause an exception in the foreach loop "foreach can not continue
because the colelction was modifed". Now what is the least expensive
and threadsafe way to make sure that no other threads modifies that
collection. Since one of the threads will do a foreach over the
collection once every 2seconds I fear doing a complete lock
(mycollection){} on the collection. Sinc I was told that this is
expensive. As far as I can see, all I need is a lock for writing, other
threads still may READ the data of the collection. Or are there any
sideeffects I might not be aware of yet? What is the best practise
here? How do I aquire a writeonly lock (in case this is the best
solution) ?
You could use a ReaderWriterLock. Another option, if there is only one
writer, but multiple readers, is that the writer could clone the
dictionary, update the clone, then replace the volatile reference to
the original dictionary with the updated dictionary. The readers would
need to obtain a local reference (by copying the volatile reference) to
the dictionary before reading, so that the reference isn't switched on
the reader in the middle of reading operations.

Aug 9 '06 #2

"bonk" <sc******************@gmx.dewrote in message
news:11**********************@m79g2000cwm.googlegr oups.com...
Hello I am acessing a Dictionary<TKey,TValuefrom multiple threads and
often in a foreach loop. While I am within one of the foreach loops the
other threads must not modify the collection itself since that would
cause an exception in the foreach loop "foreach can not continue
because the colelction was modifed". Now what is the least expensive
and threadsafe way to make sure that no other threads modifies that
collection. Since one of the threads will do a foreach over the
collection once every 2seconds I fear doing a complete lock
(mycollection){} on the collection. Sinc I was told that this is
expensive. As far as I can see, all I need is a lock for writing, other
threads still may READ the data of the collection. Or are there any
sideeffects I might not be aware of yet? What is the best practise
here?
First get a realistic estimate of the amount of lock waiting caused by a
simple exclusive locking scheme. If a thread iterates the collection every
2 seconds, and takes 10ms to iterate the collection, the collection would be
unavilable for writing 0.5% of the time. So do you really care enough to
implement a different locking scheme?
>How do I aquire a writeonly lock (in case this is the best
solution) ?
Read these for read/write locks in .NET.

ReaderWriterLock Class
http://msdn2.microsoft.com/en-us/lib...riterlock.aspx

Reader/Writer Locks and the ResourceLock Library - Jeffrey Richter
http://msdn.microsoft.com/msdnmag/is...s/default.aspx

David
Aug 9 '06 #3
Well, its not just the availability of the locked object that needs to be
taken into account. If was told that dock a lock on an object is expensive
in general. Isn't that so?
"David Browne" <davidbaxterbrowne no potted me**@hotmail.comschrieb im
Newsbeitrag news:Oz**************@TK2MSFTNGP03.phx.gbl...
>
"bonk" <sc******************@gmx.dewrote in message
news:11**********************@m79g2000cwm.googlegr oups.com...
>Hello I am acessing a Dictionary<TKey,TValuefrom multiple threads and
often in a foreach loop. While I am within one of the foreach loops the
other threads must not modify the collection itself since that would
cause an exception in the foreach loop "foreach can not continue
because the colelction was modifed". Now what is the least expensive
and threadsafe way to make sure that no other threads modifies that
collection. Since one of the threads will do a foreach over the
collection once every 2seconds I fear doing a complete lock
(mycollection){} on the collection. Sinc I was told that this is
expensive. As far as I can see, all I need is a lock for writing, other
threads still may READ the data of the collection. Or are there any
sideeffects I might not be aware of yet? What is the best practise
here?

First get a realistic estimate of the amount of lock waiting caused by a
simple exclusive locking scheme. If a thread iterates the collection
every 2 seconds, and takes 10ms to iterate the collection, the collection
would be unavilable for writing 0.5% of the time. So do you really care
enough to implement a different locking scheme?
>>How do I aquire a writeonly lock (in case this is the best
solution) ?

Read these for read/write locks in .NET.

ReaderWriterLock Class
http://msdn2.microsoft.com/en-us/lib...riterlock.aspx

Reader/Writer Locks and the ResourceLock Library - Jeffrey Richter
http://msdn.microsoft.com/msdnmag/is...s/default.aspx

David

Aug 9 '06 #4

"bonk" <bi*****@msn.comwrote in message
news:OG****************@TK2MSFTNGP04.phx.gbl...
Well, its not just the availability of the locked object that needs to be
taken into account. If was told that dock a lock on an object is expensive
in general. Isn't that so?
No. Locking objects using Monitor or lock() is not expensive.
David
Aug 9 '06 #5
bonk <bi*****@msn.comwrote:
Well, its not just the availability of the locked object that needs to be
taken into account. If was told that dock a lock on an object is expensive
in general. Isn't that so?
No. Uncontested locks are staggeringly cheap. While developing an
"improved" lock I measured the performance - I could acquire and
release a lock 22 million times in a second. Doing that once every two
seconds will give you a 0.000002% performance penalty. I would suggest
that that's not likely to be significant.
I suspect whoever told you that locks are expensive also advocates
using status codes as return values instead of throwing exceptions on
error, right?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Aug 9 '06 #6
Well, multithreaded code is usually very expensive to maintain,
especially when there is a lot of state shared between a lot of
threads. Locks are more expensive to human comprehension than to CPUs.
Like threads, locks are often overused, and misused, because simpler
solutions usually exist.

bonk wrote:
Well, its not just the availability of the locked object that needs to be
taken into account. If was told that dock a lock on an object is expensive
in general. Isn't that so?
Aug 10 '06 #7
<se***********@gmail.comwrote:
Well, multithreaded code is usually very expensive to maintain,
especially when there is a lot of state shared between a lot of
threads. Locks are more expensive to human comprehension than to CPUs.
Like threads, locks are often overused, and misused, because simpler
solutions usually exist.
On the other hand, if threading *does* need to be involved, using a
simple lock is often the easiest solution to sharing data in a thread-
safe way.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Aug 10 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: Brett Romero | last post by:
If I want to take action on the Add event of a generic Dictionary, do I need to create a custom Dictionary and add an event handler for the Add() method? The dictionary is a public field on a...
2
by: Shimon Sim | last post by:
I have Dictionary that has custom class as its key. For that class I implemented both Equals(object) and IComparable<T>. I keep getting KeyNotFoudException. What should I do? Thanks Shimon
7
by: Russell Hind | last post by:
I want to create an array of key value pairs. This code compiles fine: KeyValuePair<string, object> kvps = { new KeyValuePair<string,object>( "int", 5 ), new KeyValuePair<string,object>(...
6
by: buzzweetman | last post by:
Many times I have a Dictionary<string, SomeTypeand need to get the list of keys out of it as a List<string>, to pass to a another method that expects a List<string>. I often do the following: ...
10
by: Chris Mullins [MVP] | last post by:
KeyedCollection is a very handy little class, that unforutnatly has a nasty bug in it. The bug (which I ran across) causes the following code to fail: if (!rooms.Contains(room))...
44
by: Zytan | last post by:
The docs for List say "The List class is the generic equivalent of the ArrayList class." Since List<is strongly typed, and ArrayList has no type (is that called weakly typed?), I would assume...
4
by: Peter K | last post by:
Hi are there any benefits in using StringDictionary over Dictionary<string, string? It appears they achieve the same thing... (I could be wrong of course). thanks, Peter
6
by: daohuy.hua | last post by:
The context is that I have a C# class named MainModel which has a private Dictionary<string, FileStreammember named dict. I also have a property Dict to access to this member: public...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.