The primary mechanism for managing state in C# is through shared variables and synchronization primitives. Here we’ll look at using the System.Threading.Interlocked class for atomic counters accessed by multiple threads.
We expect to get exactly 50,000 operations. Had we used a non-atomic integer and incremented it with ops++, we’d likely get a different number, changing between runs, because the tasks would interfere with each other. Moreover, we’d get data race failures when running with tools like the Thread Sanitizer.
To run the program:
Next, we’ll look at lock statements, another tool for managing state in C#.