user99999991
user99999991

Reputation: 1421

Are there issues with locking a field while changing it's property?

private Foo _Bar;

public Foo Bar
{
  get { return _Bar; }
  set { _Bar = value; }
}

void LockAndReset()
{
   lock(_Bar)
   {
     // Some logic.
     Bar = new Foo();
   }
}

Is there anything wrong with how the lock is being used here despite the property setting _Bar field while in the lock? Is there any benefit to using a lock object instead of directly locking the field?

Upvotes: 1

Views: 44

Answers (1)

Rob
Rob

Reputation: 27367

Yes, there are problems:

Thread 1 comes in with _Bar = BarA

void LockAndReset()
{
   lock(_Bar)
   {
     Bar = new Foo();
   }
}

Thread 2 comes in with _Bar = BarA. Thread 2 is blocked until thread 1 completes.

Thread 1 sets Bar = new Foo(); (_Bar = BarB)

Now, Thread 3 comes in after Thread 1 executes Bar = new Foo();. It's now locking on BarB.

This means that thread 2 and thread 3 can both be executing within the lock at the same time, as they've grabbed different objects to lock on.

Upvotes: 2

Related Questions