Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use ReaderWriterLockSlim.EnterReadLock?

Based on Microsoft documentation EnterReadLock is used on locking in read mode. It also says multiple threads can read but only one thread can write at a time.

Why we should use EnterReadLock while multiple threads can access the same data? What happens if we don't lock on reading, but lock on writing?

like image 634
AfshinZavvar Avatar asked Nov 15 '25 17:11

AfshinZavvar


1 Answers

Read lock prevents acquiring write lock (EnterWriteLock will block until there are no more read or write locks acquired by others), but allows acquiring other read locks. If you don't use EnterReadLock on reads - the effect is other thread can acquire write lock and write data at the same time other threads read it, essentially defeating the usage of ReaderWriterLock completely.

like image 160
Evk Avatar answered Nov 17 '25 08:11

Evk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!