Updating Variables with the Interlocked ClassThe 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 bizarre value, which would be problematic if another thread read the variable at that time. The Interlocked class protects against this scenario because it makes incrementing, decrementing , and updating a variable atomic. The Interlocked class supports integers and floating- point values. Incrementing a VariableUse System.Threading.Interlocked.Increment : C# System.Threading.Interlocked.Increment(ref my_integer); VB System.Threading.Interlocked.Increment(my_integer) Decrementing a VariableUse System.Threading.Interlocked.Decrement : C# System.Threading.Interlocked.Decrement(ref my_integer); VB System.Threading.Interlocked.Decrement(my_integer) Exchanging a Value into a VariableUse System.Threading.Interlocked.Exchange : C# System.Threading.Interlocked.Exchange(ref my_integer, new_value); VB System.Threading.Interlocked.Decrement(my_integer, new_value) |