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?
is syntactic sugar for
The Monitor class holds the collection of objects that you are using to synchronize access to blocks of code. For each synchronizing object, Monitor keeps:
So, when a thread calls lock(o), it is placed in o's ready queue, until it is given the lock on o, at which time it continues executing its code.