对象参数在Monitor.Enter中的作用调用.Net

时间:2013-04-08 12:52:41

标签: c# multithreading

我们都知道下面的代码用于形成一个关键部分。

 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'的帮助下形成一个关键部分。如果我们需要总是传递一个对象,为什么cant框架显式传递任何对象。这肯定背后有一些原因。有人可以解释一下吗?

谢谢, 与Hemant

2 个答案:

答案 0 :(得分:2)

您正在传递一个对象以用作锁的标识符。考虑我有以下课程:

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)的第一个线程将阻止执行另一个线程,直到锁定在结束时释放为止。块。

答案 1 :(得分:1)

使用它以便框架知道锁的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
        }
    }
}