08 July 2008

Using ReaderWriterLockSlim

I was revisiting some code I needed to rewrite and realised I really needed to implement a locking mechanism. I remembered that of all the techniques available in the .NET framework, the System.Threading.ReaderWriterLock was going to suit the most because I needed to allow multiple concurrent reads but only one write at any time. When browsing through the class reference, I noticed a new class called ReaderWriterLockSlim and decided to have a read about it.
According to MSDN, the ReaderWriterLockSlim is a much more performant version of ReaderWriterLock and recommends developers to ditch the older class in favour of the newer one.
One tip I have is to use the TryEnterReadLock/TryEnterWriteLock methods instead of the EnterReadLock/EnterWriteLock methods. The reason is that the latter methods may end up blocking indefinitely while the former methods give you a timeout value:

lock = new ReaderWriterLockSlim();
...
if (lock.TryEnterWriteLock(1000)){
try{
//do some write operation that requires locking
}
catch(Exception e){
//handle the exception
}
finally{
lock.ExitWriteLock();
}
}
else{
//optionally throw a System.TimeoutException
}


You need to be diligent in ensuring all write operations that require locking are actually enclosed by write locks or you defeat the purpose of having a locking mechanism. The lock variable will also need to be a singleton so that locks are honoured across all threads.

No comments: