lock variable in C#
c#, design-patterns, multithreading
Solution
in the above code, i can not understand why we do not use _instance for lock variable instead of `syncLock?
Well you'd be trying to lock on a null reference, for one thing...
Additionally, you'd be locking via mutable field, which is a bad idea. (If the field changes value, then another thread can get into the same code. Not great.) It's generally a good idea to lock via a readonly field.
Also, you'd be locking on a reference which is also returned to callers, who could hold the lock for arbitrarily long periods. I prefer to lock on a reference which is never exposed outside the class - like `syncLock`.
Finally, this implementation is broken anyway due to the CLI memory model. (It may or may not be broken in the MS implementation, which is a bit stronger. I wouldn't like to bet either way.) The `_instance` variable should be marked as `volatile` if you really want to use this approach... but I'd personally avoid double-checked locking anyway. See my article on the singleton pattern for more details.
Problem
I know when to use lock block in C#, but what is not clear to me is `lock variable` in the parentheses of lock statement. Consider following `Singleton Design Pattern` from DoFactory: ``` class LoadBalancer { private static LoadBalancer _instance; private List<string> _servers = new List<string>(); private static object syncLock = new object(); public static LoadBalancer GetLoadBalancer() { // Support multithreaded applications through // 'Double checked locking' pattern which (once // the instance exists) avoids locking each // time the method is invoked if (_instance == null) { lock (syncLock) { if (_instance == null) { _instance = new LoadBalancer(); } } } return _instance; } } ``` in the above code, i can not understand why we do not use `_instance` for lock variable instead of `syncLock?