简体   繁体   中英

C# complex thread synchronization

I have quite complex threads synchronization case. I have a collection which is accessed from different threads. One thread, let's name it 'Control thread', updates a collection. Other threads read the collection ('Reading threads'). The logic I want to implement is the following:

  1. Reading threads can read the collection simultaneously.
  2. When Control thread need to update collection:
    • Control thread should not start the update until all reading threads that are currently working with collection complete their work.
    • But at the time the Control thread is waiting for finishing reading threads, other reading threads that have not started to work with collection yet, should not start - they should wait until Control thread update the collection.

What threads synchronization technique should I use?

just take a look at ReaderWriterLock Class which defines a lock that supports single writers and multiple readers or you can use ReaderWriterLockSlim (supported in .Net 4.0) which is more convenient if you are starting a new development(for example it avoids many cases of potential deadlock)

from MSDN :

ReaderWriterLockSlim is similar to ReaderWriterLock, but it has simplified rules for recursion and for upgrading and downgrading lock state. ReaderWriterLockSlim avoids many cases of potential deadlock. In addition, the performance of ReaderWriterLockSlim is significantly better than ReaderWriterLock. ReaderWriterLockSlim is recommended for all new development.*

Use the ReaderWriterLockSlim Class:

Represents a lock that is used to manage access to a resource, allowing multiple threads for reading or exclusive access for writing.

Use ReaderWriterLockSlim to protect a resource that is read by multiple threads and written to by one thread at a time. ReaderWriterLockSlim allows multiple threads to be in read mode, allows one thread to be in write mode with exclusive ownership of the lock, and allows one thread that has read access to be in upgradeable read mode, from which the thread can upgrade to write mode without having to relinquish its read access to the resource.

Joe Albahari's Threading in C# is a great resource.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM