Is there a difference between using a lock object that is declared as a field of a class as opposed to local scope?
For example: Is there a difference between using lockObject1 or lockObject2 in the below example?
public class Test()
{
private Object lockObject1 = new Object();
public void FooBar()
{
lock(lockObject1)
{
//Thread safe area 1
}
var lockObject2 = new Object();
lock(lockObject2)
{
//Thread safe area 2
}
}
}
It seems like most examples always seem to glaze over the importance of scoping of the chosen lock object.
The local lock object will not really be providing any thread safety since multiple threads running FooBar will each have their own object rather than sharing a single object for locking. (Sadly, I have seen this very thing in code headed toward production before I raised the issue and got it corrected in time.)