The following code is from MSDN:
private ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();
private Dictionary<int, string> innerCache = new Dictionary<int, string>();
public void Add(int key, string value)
{
cacheLock.EnterWriteLock();
try
{
innerCache.Add(key, value);
}
finally
{
cacheLock.ExitWriteLock();
}
}
I’ve seen code like this in other places.The EnterWriteLock() is always outside the try block. Does anyone know why it’s not inside the try block?
Suppose the
EnterWriteLock()fails. For whatever reason.Then the one thing you shouldn’t do is to Exit a lock you never Entered.
It’s a very basic pattern that also holds for example for streams, but not seen as often thanks to the
using() {}statement.