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:
Post a Comment