I once read a very good explanation on so called non-atomic and atomic (in VB: interlocked) operations and will try to sum that up.
Normal "non-atomic" operations consist of several steps
-> other threads can work in between those streps
"Atomic" operations consist of one only one step
-> other threads cannot perform work while atomic operations are processed, atomic operations are always processed as whole
The interlocked class is a collection of such atomic operations and therefor threadsafe by definition.
Even with multiple threads performing read and write operations on the same variable, these operations are absolutely thread safe.
Still a combination of those threadsafe commands can be unsafe, as race conditions can occur in between the atomic operations.
So if you want to for example compare 2 variables and then increment the smaller one, this is not thread safe even though the single operations for themself are (interlocked.compare, interlocked.increment).
Here you still have to use synclocks.
Other than that limitation there is no "hidden bad side" of interlocked.
One example for a racecondition with a = 5:
Thread1: a+=1
Thread2: a+=2
--> supposed to be 8, but can be only 6 or 7,
but can also be 6 or 7 depending on which thread wins the race
option 1:
T1 step 1: read 5
T1 step 2: add 1 = 6
T1 step 3: write 6
T2 step 1: read 6
T2 step 2: add 2 = 8
T2 step 3: write 8
--> is 8 as supposed
or option 2:
T1 step 1: read 5
T2 step 1: read 5
T1 step 2: add 1 = 6
T2 step 2: add 2 = 7
T2 step 3: write 7
T1 step 3: write 6
--> is only 6
or option 3:
T1 step 1: read 5
T2 step 1: read 5
T1 step 2: add 1 = 6
T2 step 2: add 2 = 7
T1 step 3: write 6
T2 step 3: write 7
--> is only 7
With interlocked.increment:
option 1:
T1 step 1: read 5, add 1, write 6
T2 step 1: read 6, add 2, write 8
or option 2:
T2 step 1: read 5, add 2, write 7
T1 step 1: read 7, add 1, write 8
-> in all cases a = 8 as supposed, threadsafe solution
All the questions that were posted here can be solved by applying this simple example to the questionable code.
Hope this helps other people who google this topic.
Janis