对象参数在Monitor.Enter调用.Net中的作用 [英] Role of object parameter in Monitor.Enter call .Net
问题描述
我们都知道下面的代码用于构成关键部分.
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);
}
}
我的问题是Monitor.Enter如何在'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?
谢谢, 赫曼特(Hemant)
Thanks, Hemant
推荐答案
您正在传递一个对象,以用作锁的标识符.考虑一下我上了以下课程:
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)
{
...
}
}
}
如果我要从不同的线程调用Method1
和Method2
,则这两个调用都将阻塞另一个对象,因为它们锁定在不同的对象上.但是,如果我要从不同的线程调用Method1
和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.
这篇关于对象参数在Monitor.Enter调用.Net中的作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!