What is the point of using a non-static local variable in a lock?

Several times I came across this code where a local variable in the class (its NOT a static variable) was used in the lock.

public class SomeClass { private object obj = new object(); .... .... lock(obj) { } } 

Is there any lockpoint given its instance variables?

+6
synchronization c #
source share
2 answers

Is there any lockpoint given its instance variables?

Multiple threads can affect the same instance, and blocking is required to ensure thread safety. Think, for example, of a common queue.

+14
source share

Static locking will be useful for controlling access to a static variable. Instance locking would be useful for controlling access to an instance variable.

It makes no sense to use a local lock object to protect a local variable (unless it is an anonymous function captured by an external variable or an iterator), since other threads will not have access to the lock, nor to the variable.

+5
source share

All Articles