lock marks a statement block as critical section and ensures one thread doesn’t enter critical section with another thread.
lock can be applied on an object. Avoid lock on public type. Below lock should be avoided:
- lock (this) is a problem if the instance can be accessed publicly.
- lock (typeof (MyType)) is a problem if MyType is publicly accessible.
- lock(“myLock”) is a problem because any other code in the process using the same string, will share the same lock.
Best practice is to define private object or private static object variable to protect data common to all instance.
class Account { decimal balance; private Object thisLock = new Object(); public void Withdraw(decimal amount) { lock (thisLock) { if (amount > balance) { throw new Exception("Insufficient funds"); } balance -= amount; } } }
for more explanation refer:
http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx