C# - Lock question using EnterWriteLock
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 EnterWriteLo开发者_StackOverflow中文版ck() 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.
var s = File.Create(...);
// (only) if the previous line succeeded,
// we gain the responsibility to close s, no matter what
try
{
// do some I/O
}
finally
{
s.Dispose();
}
Because that would be a bug. You can't call ExitWriteLock until you're sure that you entered it. Imagine what happens if you moved it inside try {} and EnterWriteLock() throws an exception. That's a double kaboom. Kabloom, screws up the exception message.
If EnterWriteLock throws an exception, there is no need to call ExitWriteLock, hence the reason it is not in the try block. ExitWriteLock should always be called if EnterWriteLock is successfully invoked. You may want to wrap a try block around EnterWriteLock in certain scenarios as it can throw a LockRecursionException. ExitWriteLock can also throw a SynchronizationLockException and may require a try block in your application.
精彩评论