R
Richard.Haggard
Guest
If an exception is thrown within a lock block is the lock released or not?
Example of a class wherein exceptions will easily be thrown while a lock is in effect:
namespace Utils
{
public class ThreadSafeDictionary<TKey, TValue>
{
private object LockObj = new object();
private Dictionary<TKey, TValue> Dic = new Dictionary<TKey, TValue>();
public TValue this[TKey key]
{
get
{
TValue val = default(TValue);
lock(LockObj)
{
// What if an exception happens?
// Will LockObj be released?
val = Dic[key];
}
return val;
}
set
{
lock (LockObj)
{
// What if an exception happens?
// Will LockObj be released?
Dic[key] = value;
}
}
}
}
}
Richard Lewis Haggard
Continue reading...
Example of a class wherein exceptions will easily be thrown while a lock is in effect:
namespace Utils
{
public class ThreadSafeDictionary<TKey, TValue>
{
private object LockObj = new object();
private Dictionary<TKey, TValue> Dic = new Dictionary<TKey, TValue>();
public TValue this[TKey key]
{
get
{
TValue val = default(TValue);
lock(LockObj)
{
// What if an exception happens?
// Will LockObj be released?
val = Dic[key];
}
return val;
}
set
{
lock (LockObj)
{
// What if an exception happens?
// Will LockObj be released?
Dic[key] = value;
}
}
}
}
}
Richard Lewis Haggard
Continue reading...