对象参数在Monitor中的角色.输入call . net

本文关键字:角色 输入 call net 参数 Monitor 对象 | 更新日期: 2023-09-27 18:08:16

我们都知道下面的代码是用来形成临界区的。

 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);
    }
}

我的问题是如何监控。Enter在'obj'的帮助下形成一个临界区。如果我们总是需要传递一个对象,为什么框架不能显式地传递任何对象呢?这背后肯定有什么原因。有人能解释一下吗?

谢谢,赫曼特

对象参数在Monitor中的角色.输入call . net

传递一个对象作为锁的标识符。考虑我有以下类:

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)
        {
            ...
        }
    }
}

如果我从不同的线程调用Method1Method2,两个调用都不会阻塞另一个,因为它们锁在不同的对象上。但是,如果我要从不同的线程调用Method1Method3,那么执行lock(obj1)的第一个线程将阻塞另一个线程的执行,直到在块结束时释放锁。

这样框架就知道锁的scope

基本上,您想要使用静态对象或非静态对象。

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
        }
    }
}