views:

29

answers:

3

I have a 2nd thread where i run a never ending loop (it listens to incoming TCP request).

In that thread/loop i update a dictionary with holds my core data. In my winform GUI i would like to access the dictionary and display info. However if i write a foreach loop i get the exception that the dictionary has been modified.

How do i safely access that dictionary? I tried clone but there is no clone method. I dont want a lock to access it. I wanted to do something like invoke however it doesnt appear i can invoke a function in a thread?

So how do i access this?

+3  A: 

If you're using .NET 4, you could use ConcurrentDictionary. Otherwise, I think you've really got to lock it.

You could build your own invocation mechanism to marshal a call to the other thread, but that's likely to be tricky.

If you're worried about locking for performance reasons, it's worth checking whether or not your concerns are justified. If you make sure that anywhere you take out the lock you only do so for a very short time, you may well be fine. One thing would be to create a copy of the dictionary using the appopriate constructor:

Dictionary<Foo, Bar> copy = new Dictionary<Foo, Bar>(existing);

Note that you'll still need to make sure you have exclusive access to the dictionary during construction - but then you can release the lock and use the copy to your heart's content. Of course, if the keys and values are mutable, you've got another set of problems...

Jon Skeet
Locking copy with constructor + unlocking seems best. I like it. I'm surprised i havent copied a dictionary or list with a ctor before.
acidzombie24
+2  A: 

If possible then I recommend to switch to .net 4, it have bunch of updated related to parallel programming, including ConcurrentDictionary.

If not, you can check the following answer: whats-the-best-way-of-implementing-a-thread-safe-dictionary-in-net

arbiter
+1 but i did notice a lock in that thread safe implementation.
acidzombie24
A: 

You could make your own implementation of IDictionary<TKey, TValue> where you control the concurrent operations.

http://msdn.microsoft.com/en-us/library/system.collections.idictionary.aspx

Nubsis
to much work, i'm lazy. also i dont want to F it up. Skeet idea with copy in a constructor and locking for a short time is what i like best.
acidzombie24