Interlocked Helpers

Looking back at our counter example, recall the core issue that made synchronization required to produce the right result. Some essential operations, such as increment and decrement of an integer value, didn’t run atomically, which might have surprised many readers. Why is it that those simple operations can cause tremendous grief? The answer lies in their definition from a C# language point of view.

In particular, i++ is merely a shortcut for i += 1, which on its turn is shorthand syntax for i = i + 1. Notice how we ignore the capability of such an increment expression to be used, well, as an expression. But the fundamental fact remains that such expressions are shorthand syntax for a sequence of mutation operations. This ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.