Consider this piece of code that creates a closure around counter:
uint counter = 0xFFFF;
someList.AsParallel().ForEach(a => { uint tmp = ++counter });
(Please put aside the obvious problem of using a counter in parallel foreach for a minute).
Will it tmpever be evaluated to 0x0000 or 0x1FFFF?
My reasoning: to increase counterfrom 0xFFFF to 0x10000, at least a two-byte CPU command is required, which can be interrupted by multi-threaded processing. If it is interrupted, there is a possibility that only one byte will be updated counter- it can be temporarily set to 0x00000 or 0x1FFFF.
Should I write this as:
uint counter = 0xFFFF;
someList.AsParallel().ForEach(a => { uint tmp = Interlocked.Increment(counter) });
...
And if I get rid of AsParallel, am I completely safe?