Roey Nissim
Roey Nissim

Reputation: 555

setting the lock to null

Is this legal? (i.e. setting the lock to 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;
            }
        }
    }
}

Upvotes: 3

Views: 2370

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186718

The direct experiment you could have carried out shows that lock(null) throws ArgumentNullValueException. Another issue is that your code has a syntax error:

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

A typical way for using lock is

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

Upvotes: 0

Dariusz
Dariusz

Reputation: 22261

This would be legal if a wasn't a local variable in the constructor but a field.

Lock is initiated on a valid object. The reference is then nulled, but the lock still operates on the previous non-null value.

However if another lock attempt was made, it would end up being an error. See this question: Why doesn't C# allow a null value to be locked?

Upvotes: 3

Related Questions