I\'m wondering if this construction will cause an error:
lock(sync)
{
// something
lock(sync)
{
//something
lock(sync)
{
//something
To explain why it is well-defined behavior and will never fail:
Aside: This answer has better details about how locks actually work
The lock occurs at the Thread
level, so calling it a second time on the same thread will be redundant. I would think it would not have any performance penalty (although that would depend on how exactly the internals of .Net are written, so I can't guarantee that)
Many times you'd have a public function that calls another public function in your class, whom both need the lock when used seperately. If this was not allowed the following would fail:
private Dictionary database = new Dictionary();
private object databaseLock = new object();
public void AddOrUpdate(string item)
{
lock (databaseLock)
{
if (Exists(item))
database.Add(item, 1);
else
++database[item];
}
}
public bool Exists(string item)
{
lock (databaseLock)
{
//... Maybe some pre-processing of the key or item...
return database.ContainsKey(item);
}
}