将锁设置为null

时间:2013-12-26 11:00:22

标签: c# null locking

这合法吗? (即将锁设置为null)

Class A
{
    public A() { }

    // Some stuff
}

Class B
{
    A a;

    public B()
    {
        A a = new A();
    }

    public void ResetA()
    {
        lock(a)
        {
            if(a != null)
            {
                a = null;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

如果a不是构造函数中的局部变量而是字段,那么将是合法的。

在有效对象上启动锁定。然后将引用置为空,但锁仍然对先前的非空值进行操作。

但是,如果进行了另一次锁定尝试,则最终会出错。请参阅此问题:Why doesn't C# allow a null value to be locked?

答案 1 :(得分:0)

您可以执行的直接实验表明lock(null)会抛出 ArgumentNullValueException 。另一个问题是您的代码有语法错误:

  public void ResetA() {
    lock(a) { ... // <- a is undefined; probably "B" class should have "A a" field 

使用 lock 的典型方法是

Class B {
  // Object to be used in locking.
  // It's private: we don't want to let anyone
  // interfere in our internal locking policy 
  // (so we do not use e.g. lock(this) etc)  
  private Object m_SyncObj = new Object();

  A a = new A();

  public void ResetA() {
    lock (m_SyncObj) {
      // A little bit strange lock block unless "a" is locked somewhere else as well
      a = null;
    }
  }
...