Interlocked.Decrement Method (Int32)


Decrements a specified variable and stores the result, as an atomic operation.

Namespace:   System.Threading
Assembly:  mscorlib (in mscorlib.dll)

static member Decrement : 
        location:int byref -> int


Type: System.Int32

The variable whose value is to be decremented.

Return Value

Type: System.Int32

The decremented value.

Exception Condition

The address of location is a null pointer.

This method handles an overflow condition by wrapping: If location = Int32.MinValue, location - 1 = Int32.MaxValue. No exception is thrown.

The following example determines how many random numbers that range from 0 to 1,000 are required to generate 1,000 random numbers with a midpoint value. To keep track of the number of midpoint values, a variable, midpointCount, is set equal to 1,000 and decremented each time the random number generator returns a midpoint value. Because three threads generate the random numbers, the Decrement(Int32) method is called to ensure that multiple threads don't update midpointCount concurrently. Note that a lock is also used to protect the random number generator, and that a CountdownEvent object is used to ensure that the Main method doesn't finish execution before the three threads.

No code example is currently available or this language may not be supported.

The following example is similar to the previous one, except that it uses the instead of a thread procedure to generate 50,000 random midpoint integers. In this example, a lambda expression replaces the GenerateNumbers thread procedure, and the call to the Task.WaitAll method eliminates the need for the CountdownEvent object.

No code example is currently available or this language may not be supported.

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top