MSDN Documentation and many examples of using ReaderWriterLockSlim
class recommends using the following pattern:
cacheLock.EnterWriteLock();
try
{
//Do something
}
finally
{
cacheLock.ExitWriteLock();
}
But I'm curious if it's completely safe. Is it possible that some exception will happen after lock is acquired, but before the try
statement so that lock is stuck in the locked state? The most obvious candidate is ThreadAbortException
. I understand that probability of this situation is extreemely small, but the consequences are extreemely bad - so I think it worth thinking about it. I don't believe compiler understands this pattern and prevents processor from interrupting thread before try
statement.
If there is theoretical possibility that this code is unsafe, and is there ways to make it safer?