Updating Variables with the Interlocked Class

The System.Threading.Interlocked class provides means to increment, decrement, and set a variable in a thread-safe manner. When a variable is incremented or decremented with the Interlocked class, the process is atomic. The CPU cannot be taken away while the increment or decrement is in progress.

Why is this important? Consider an application with one thread that can update an integer and many threads that can read it. On the surface this seems like a safe arrangement. However, consider what would happen if a thread updated a variable in a process that took several CPU instructions, and the CPU was taken away before the update finished. At this instant the variable could have an unexpected, often ...

Get Microsoft® .NET Compact Framework Kick Start 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.