I’m still confused… When we write some thing like this:
Object o = new Object(); var resource = new Dictionary<int , SomeclassReference>();
…and have two blocks of code that lock o while accessing resource…
//Code one lock(o) { // read from resource } //Code two lock(o) { // write to resource }
Now, if i have two threads, with one thread executing code which reads from resource and another writing to it, i would want to lock resource such that when it is being read, the writer would have to wait (and vice versa – if it is being written to, readers would have to wait). Will the lock construct help me? …or should i use something else?
(I’m using Dictionary for the purposes of this example, but could be anything)
There are two cases I’m specifically concerned about:
- two threads trying to execute same line of code
- two threads trying to work on the same resource
Will lock help in both conditions?
Most of the other answers address your code example, so I’ll try to answer you question in the title.
A lock is really just a token. Whoever has the token may take the stage so to speak. Thus the object you’re locking on doesn’t have an explicit connection to the resource you’re trying to synchronize around. As long as all readers/writers agree on the same token it can be anything.
When trying to lock on an object (i.e. by calling
Monitor.Enteron an object) the runtime checks if the lock is already held by a thread. If this is the case the thread trying to lock is suspended, otherwise it acquires the lock and proceeds to execute.When a thread holding a lock exits the lock scope (i.e. calls
Monitor.Exit), the lock is released and any waiting threads may now acquire the lock.Finally a couple of things to keep in mind regarding locks:
Monitor.Enter/Exitinstead of thelockkeyword, be sure to place the call toExitin afinallyblock so the lock is released even in the case of an exception.