I’d like to know how you know when to lock an entire type
lock (typeof(MyClass))
{
...
}
or an instance
lock (this)
{
...
}
or an object
lock (this._lockObj)
{
...
}
I am asking this because I have a static class that is a simple Wrapper for Enterprise Library 5 and is accessed by multiple components from possibly different threads. The WriteLog() method is locked. I use the type to lock.
First rule. Lock using object that is not accessible from outside of class. That’s why
thisand varioustypeofs are bad idea. Outer code can interfere with your locks. Then question is what scope oflockis it. If it is static then use static field otherwise use instance field.To pick correct
lockobject you should you identify groups of code that are mutually exclusive. So if you have 4 methods that are exclusive in pairs like A and B , C and D you should have 2 differenetlockobjects, not 1.