If you have ever used the System.Threading.ReaderWriterLock to achieve synchronised access to shared resources which are frequently read but infrequently updated then you probably know why we have created a new Reader/Write lock. In this MSDN Magazine’s concurrent affairs column, Jeffery Richter explains some of the short comings of the existing ReaderWriterLock in .NET Framework.
One of the hidden gems of the new .NET Framework 3.5 is a fast Reader/Writer lock called “ReaderWriterLockSlim”. If you are not familiar with this new lock then read this blog entry.
Before recommending this new lock to my customers, I wanted to see some comparisons with Monitor and the existing ReaderWriterLock. So, I devised the following comparison tests:
- Acquiring a Read lock in comparison with taking a lock using Monitor
- Acquiring a Write lock in comparison with taking a lock using Monitor
- Acquiring a Read/Write lock in comparison with taking a Read/Write lock using ReaderWriterLock
After executing the test for 1000 times, it became apparent that ReaderWriterLockSlim with no recursion support is 1.67 times slower than Monitor and it is 1.74 times slower when recursion is supported:
ReaderWriterLockSlim, in average, is 1.71 times slower than Monitor, and when recursion is supported it is 1.77 times slower.
It also turns out that acquiring a Read lock using the new slim lock class is slightly quicker than taking a Write lock.
ReaderWriterLock is significantly slower than its successor:
- Taking a ReaderWriterLockSlim Read lock is almost 3 times quicker than ReaderWriterLock
- Taking a ReaderWriterLockSlim Write lock is 2.8 times quicker than ReaderWriterLock
The table below compares both Reader/Writer locks with Monitor:
Monitor
ReaderWriterLock
ReaderWriterLockSlim (No recursion support)
ReaderWriterLockSlim (recursion support)
Read
1
5
1.67
1.74
Write
4.71
1.71
1.77