Reputation: 174
What is the best way to have synchronized a collection of objects between various threads in .Net?
I need to have a List or Dictionary accessed from different threads in a thread safe mode. With Adds, Removes, Foreachs, etc.
Upvotes: 1
Views: 322
Reputation: 30790
Basically it depends on the pattern you need to use. If you have several threads writing and reading the same place you can use the same data structure that you would have used with a single thread (hastable, array, etc.) with a lock/monitor or a ReaderWriterLock to prevent race conditions. In case you need to pass data between threads you'll need some kind of queue (synced or lockfree) that thread(s) of group A would insert to and thread(s) of group B would deque from. You might want to use WaitEvent (AutoReset or Manual) so that you won't loose CPU when the queue is empty. It really depends on what kind of workflow you want to achieve.
Upvotes: 1
Reputation: 1439
Without knowing specifics, I'd lean towards delegates and events to notify of changes.
http://msdn.microsoft.com/en-us/library/17sde2xt(VS.71).aspx
And implementing the Observer or Publish Subscribe pattern
http://en.wikipedia.org/wiki/Observer_pattern http://msdn.microsoft.com/en-us/library/ms978603.aspx
Upvotes: 0
Reputation: 4720
A number of the collection classes in .Net have built in support for synchronizing and making access from multiple threads safe. For example (in C++/CLR):
Collections::Queue ^unsafe_queue = gcnew Collections::Queue();
Collections::Queue ^safe_queue = Collections::Queue::Synchronized(unsafe_queue);
You can throw away the reference to unsafe_queue, and keep the reference to safe_queue. It can be shared between threads, and you're guaranteed thread safe access. Other collection classes, like ArrayList and Hashtable, also support this, in a similar manner.
Upvotes: 0
Reputation: 97849
Hashtable.Synchronized method returns a synchronized (thread safe) wrapper for the Hashtable.
http://msdn.microsoft.com/en-us/library/system.collections.hashtable.synchronized(VS.80).aspx
This also exists for other collections.
Upvotes: 0
Reputation: 103325
You could implement a lock-free queue:
http://www.boyet.com/Articles/LockfreeQueue.html
Or handle the synchronization yourself using locks:
http://www.albahari.com/threading/part2.html#_Locking
Upvotes: 0