Thread Safe Properties in C#

The locks, as you have written them are pointless. The thread reading the variable, for example, will:

  1. Acquire the lock.
  2. Read the value.
  3. Release the lock.
  4. Use the read value somehow.

There is nothing to stop another thread from modifying the value after step 3. As variable access in .NET is atomic (see caveat below), the lock is not actually achieving much here: merely adding an overhead. Contrast with the unlocked example:

  1. Read the value.
  2. Use the read value somehow.

Another thread may alter the value between step 1 and 2 and this is no different to the locked example.

If you want to ensure state does not change when you are doing some processing, you must read the value and do the processing using that value within the contex of the lock:

  1. Acquire the lock.
  2. Read the value.
  3. Use the read value somehow.
  4. Release the lock.

Having said that, there are cases when you need to lock when accessing a variable. These are usually due to reasons with the underlying processor: a double variable cannot be read or written as a single instruction on a 32 bit machine, for example, so you must lock (or use an alternative strategy) to ensure a corrupt value is not read.

Leave a Comment