Updating Variables with the Interlocked Class


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 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 Variable

Use System.Threading.Interlocked.Increment :

 
 C# System.Threading.Interlocked.Increment(ref my_integer); VB System.Threading.Interlocked.Increment(my_integer) 

Decrementing a Variable

Use System.Threading.Interlocked.Decrement :

 
 C# System.Threading.Interlocked.Decrement(ref my_integer); VB System.Threading.Interlocked.Decrement(my_integer) 

Exchanging a Value into a Variable

Use System.Threading.Interlocked.Exchange :

 
 C# System.Threading.Interlocked.Exchange(ref my_integer, new_value); VB System.Threading.Interlocked.Decrement(my_integer, new_value) 


Microsoft.NET Compact Framework Kick Start
Microsoft .NET Compact Framework Kick Start
ISBN: 0672325705
EAN: 2147483647
Year: 2003
Pages: 206

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net