问题
we all know below code is used to form a critical section.
public class CommonResource
{
public object obj = new object();
public void PopularFunction()
{
lock (obj)
{
///Access variable that we want to protect form being accessed concurrently
///This forms critical section
///My question is what is role'obj' plays in forming critical section.
///How it works behind the scene.
}
///Above code can be written as
Monitor.Enter(obj);
///Access variable that we want to protect form being accessed concurrently
///This forms critical section
///My question is what is role'obj' plays in forming critical section.
///How it works behind the scene.
Monitor.Exit(obj);
}
}
My question is how does Monitor.Enter forms a critical section with the help of 'obj'. If we need to always pass an object why cant framework explicitly pass any object. Definitely there has to be some reason behind this. Can anybody explain?
Thanks, Hemant
回答1:
You're passing an object to use as an identifier for the lock. Consider I had the following class:
public class LockTest
{
private object obj1 = new object();
private object obj2 = new object();
public void Method1()
{
lock(obj1)
{
...
}
}
public void Method2()
{
lock(obj2)
{
...
}
}
public void Method3()
{
lock(obj1)
{
...
}
}
}
If I were to call Method1
and Method2
from different threads, neither call would block the other, since they're locking on different objects. If, however, I were to call Method1
and Method3
from different threads, the first thread to execute the lock(obj1)
would block execution of the other thread until the lock was released at the end of the block.
回答2:
It is used so the framework knows the scope
of the lock.
Basically, you want to either use a static object or a non-static object.
public class Foo
{
private object sync = new object();
public void Bar()
{
lock (this.sync)
{
// You can call new Foo().Bar() multiple times, because
// each Foo class lock its own instance of the sync object
}
}
}
public class Foo
{
private static object sync = new object();
public void Bar()
{
lock (sync)
{
// You can't call new Foo().Bar() multiple times, because
// each Foo class lock the same instance of the sync object
}
}
}
来源:https://stackoverflow.com/questions/15879561/role-of-object-parameter-in-monitor-enter-call-net