473,734 Members | 2,788 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 6138
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 ReaderWriterLoc k. 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.dewr ote in message
news:11******** **************@ m79g2000cwm.goo glegroups.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.

ReaderWriterLoc k 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" <davidbaxterbro wne no potted me**@hotmail.co mschrieb im
Newsbeitrag news:Oz******** ******@TK2MSFTN GP03.phx.gbl...
>
"bonk" <sc************ ******@gmx.dewr ote in message
news:11******** **************@ m79g2000cwm.goo glegroups.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.

ReaderWriterLoc k 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.co mwrote in message
news:OG******** ********@TK2MSF TNGP04.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.co mwrote:
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.co m>
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.co m>
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
21398
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 custom control. Thanks, Brett
2
1756
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
25695
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>( "string", "robot") }; But is their no shorthand to this such as KeyValuePair<string,object> kvps = {{"int",5 },{"string","a string"}};
6
46186
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: <BEGIN CODE> List<stringkeyNameList = new List<string>(); foreach (string keyName in this.myDictionary.Keys)
10
3785
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)) _rooms.Add(room); The problem is that contains returns "false", but then Add throws an exception because the item really is already in there.
44
39178
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 List<is far better. So, why do people use ArrayList so often? Am I missing somehing? What's the difference between them? Zytan
4
10681
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
1814
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 Dictionary<string, FileStreamDict { get { return this.dict; } } The problem with this implementation is that I only want to give
0
8946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8776
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9236
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9182
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6735
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6031
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.