1

How to know if a ReaderWriterLockSlim is currently write-locked by another thread?

ReaderWriterLockSlim rwls = new ReaderWriterLockSlim()
var i = rwls.CurrentReadCount; 
// count of reading threads (but unfortunately there's no CurrentWriteCount property)
var j = rwls.IsWriteLockHeld; 
// check if current thread is holding the lock (limited to current thread)

/* none of above can do it */

yes I can call rwls.TryEnterWriteLock(1) to check if it is write-locked but that will slow down the performence

are there any direct way to get write-lock status ?

ineztia
  • 815
  • 1
  • 13
  • 29
  • 1
    What about the performance of `rwls.TryEnterWriteLock(0)`? Have you tested that to see if it is acceptable. However, you need to ask yourself, do you really need to check without taking a lock, the next line of code you execute your check is considered stale and may not be accurate anymore. – Scott Chamberlain Apr 04 '16 at 04:45
  • I implemented a list of RWLocks to moninor groups of resources, to avoid memory issue (as size of rwlock list increased), I have to manually scanvage the list at some certain time and do that check before element removing action. @ScottChamberlain – ineztia Apr 04 '16 at 05:08
  • btw: for some reason I can't use ConditionalWeakTable instead of list to get auto GC benefit – ineztia Apr 04 '16 at 05:22

0 Answers0