Under the Hood
You might, and actually should, wonder where this nondeterminism comes from. To understand this, we need to delve a little deeper. The crux of the problem lies in the fact Increment
and Decrement
are not atomic operations:
public void Increment(){ _value++;}
The use of the post-increment expression (used as a statement here) really decomposes in three distinct operations that are carried out sequentially: First the value is read, then it gets incremented, and finally it gets assigned back to the field. Figure 8.24 shows the IL code corresponding to a post-increment expression.
Figure 8.24. Non-atomic post-increment on a field.
It’s worth the effort to try to understand this code fully. And how better than to show it with an ...
Get C# 4.0 Unleashed now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.