Enable C # To easily implement read/write lock separation-encapsulate ReaderWriterLockSlim

Source: Internet
Author: User

The ReaderWriterLockSlim class is used to manage the lock status of resource access, and supports multi-threaded reading or exclusive write access. ReaderWriterLockSlim is used to protect resources read by multiple threads but written by only one thread at a time. ReaderWriterLockSlim allows multiple threads to be in Read mode, allows a thread to be in write mode and exclusively locked, and allows a thread with read permission to be in upgradeable read mode, in this mode, the thread can upgrade to the write mode without giving up the read permission on the resource. Note that ReaderWriterLockSlim is similar to ReaderWriterLock, But it simplifies the recursion, upgrade, and downgrade lock status rules. ReaderWriterLockSlim can avoid multiple potential deadlocks. In addition, ReaderWriterLockSlim has better performance than ReaderWriterLock. We recommend that you use ReaderWriterLockSlim in all new development work. The above reference is from MSDN ps: this class is in. provided in NET3.5. If you need to use ReaderWriterLock in 2.0, you need to change the write method name. In MSDN, ReaderWriterLockSlim has a high performance primary attribute. Method attribute: IsReadLockHeld to get a value, this value indicates whether the current thread is locked in Read mode. IsWriteLockHeld gets a value indicating whether the current thread is locked in write mode. Method: EnterReadLock tries to enter the Read mode lock status. ExitReadLock reduces the recursive count in Read mode and exits read mode when the generated count is 0 (zero. EnterWriteLock tries to enter the write mode lock status. ExitWriteLock reduces the recursive count of the write mode and exits the write mode when the generated count is 0 (zero. Of course there are many other methods, such as EnterUpgradeableReadLock entering the Read mode that can be upgraded to the write mode .. however, the objects to be encapsulated are relatively simple, so these additional methods and attributes are not required, if you are interested, you can study the application on your own to compare the old lock statement private object _ Lock = new object (); private void Read () {lock (_ Lock) {// specific method Implementation} private void Write () {lock (_ Lock) {// specific method Implementation} read/Write lock separation private ReaderWriterLockSlim _ LockSlim = new ReaderWriterLockSlim (); private void Read () {try {_ LockSlim. enterReadLock (); // method Implementation} finally {_ LockSlim. exitReadLock () ;}} private void Write () {try {_ LockSlim. enterWriteLock (); // method Implementation} finally {_ LockSlim. exitWriteLock () ;}}: From the performance perspective, it must be better to separate the read/write locks, especially in most cases (read operations are far from redundant write operations) in terms of readability and code aesthetics, the lock above should be much simpler and clearer in maintenance, so I hope to re-encapsulate ReaderWriterLockSlim. Of course, the first thing I think of is using, the using syntax sugar feature encapsulates a new object encapsulation Code platform: UsingLock is called UsingLock because it uses the using syntax. It is easy to remember the UsingLock source Code method: Read () in read lock mode, Write () enters Write lock mode. In addition, I add two additional attributes, Data UsingLock, to save one Data, the environment in the current thread determines whether the object can be read or set to Enabled to enable the current component .. this is an amazing use. Here we will introduce the usage of MyQueue. I assume a queue system here to publish the two operations that are most prone to problems: modifying the set and enumerating the set, the test code is as follows: static void Main (string [] args) {// creates a string set, the total number is 1000 List <string> list = new List <string> (1000); for (int I = 0; I <list. capacity; I ++) {list. add ("string:" + I);} MyQueue mq = new MyQueue (list); // save the last value and use it to compare string last = list [list. count-1]; // start 1000 threads, execute the LootFirst method at the same time, and print the result for (int I = 0; I <list. capacity; I ++) {ThreadPool. queueUserWorkItem (o =>{ Console. writeLine (mq. lootFirst ();} // the mq Traversal method is continuously called in the main thread. Such an operation is prone to thread contention for resources. If the access mechanism is not locked, the while (mq. count> 0) {foreach (var item in mq) {// if the last value is still present, output "still in" if (item = last) {Console. writeLine ("still ");}}}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.