Reputation: 3834
I am having some doubts while using lock statement
to make thread safe, here is my code:
public class Class1
{
public ClassName _Obj;
private static object LockObj = new object();
public ClassName Obj
{
get { return _Obj ?? (_Obj = new ClassName()); }
}
public void ThreadA()
{
//lock (LockObj) --able to handle the thread
//lock (Obj) --it is also able to handle the thread
lock (this) // --same for this also
{
for (int i = 0; i < 1000; i++)
{
Obj.ValueA = i;
// Processing on Obj..
}
}
}
}
public class ClassName
{
public int ValueA { get; set; }
}
In this block of code ThreadA
can be made safe by using a lock
statement. But which is the exact way of passing an argument to the lock statement? The same result can be achieved by passing ClassName
object i.e Obj
, LockObj
object which is static or by this
object also. Please make it clear, which is better and why?
Upvotes: 0
Views: 127
Reputation: 75326
From MSDN to explain lock
statement:
In general, avoid locking on a public type, or instances beyond your code's control. The common constructs lock (this), lock (typeof (MyType)), and lock ("myLock") violate this guideline:
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 a private object to lock on, or a private static object variable to protect data common to all instances.
Upvotes: 2