The ReaderWriterLockSlim class is a powerful class used for thread synchronizations.
According to the documentation:
“It is used 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.”
It’s much faster than ReaderWriterLock Class and easier to understand, and as a result it will probably be your first choice when you want to synchronize reads/writes.
The main problem of the ReaderWriterLockSlim is that using it is not that simple, and requires code repetition for each use.
Here is a basic example for getting and setting an object:
As you see, each time you need to access the object, you need to wrap it in a try-finally block.
When required to use the EnterUpgradeableReadLock method as well, the code might become really messy.
The solution is to introduce the SafeReaderWriterLockSlim class. The SafeReaderWriterLockSlim class cleans the code, and helps the developer focus on the real business value.
The SafeReaderWriterLockSlim inherits from the SafeReaderWriterLock class and adds the functions SafeEnterReadLock, SafeEnterWriteLock and SafeEnterUpgradeableReadLock. Each of these functions gets a parameter of type Action, and encapsulates the try catch block. They might also get a TimeSpan parameter, and in this case they execute the Try version of their corresponding function.
Here is the implementation of SafeEnterReadLock
|And here is the previous sample using the SafeReaderWriterLockSlim
You can see that even in this simple example, the code became much simpler and easy to read.
You can find the source code for SafeReaderWriterLockerSlim here