O'Reilly logo

C# in a Nutshell by Peter Drayton, Ted Neward, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

Interlocked

Synopsis

The static members of this class provide thread safety for common built-in arithmetic operations, such as ++, --, and exchanging variables.

If two threads increment the same variable, one thread could be interrupted after both have retrieved the initial value of the variable. If this happens, then both operations store the same value, meaning that the variable has been incremented once instead of twice. The Interlocked methods protect against this kind of error. Increment() and Decrement() replace ++ and --, respectively, and Exchange() switches two variables. CompareExchange() compares the first two variables and, if true, assigns the third value to the first variable.

public sealed class Interlocked {
// Public Static Methods
   public static method int CompareExchange(ref int location1, 
        int value, int comparand);  
   public static method object CompareExchange(
        ref object location1, object value, 
        object comparand);  
   public static method float CompareExchange(
        ref float location1, float value, 
        float comparand);  
   public static method int Decrement(ref int location);  
   public static method long Decrement(ref long location);  
   public static method int Exchange(ref int location1, 
        int value);  
   public static method object Exchange(ref object location1, 
        object value);  
   public static method float Exchange(ref float location1, 
        float value);  
   public static method int Increment(ref int location);  
   public static method long Increment(ref long location);  
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required