Interlocked::Increment Method (Int32%)

 

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

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

public:
static int Increment(
	int% location
)

Parameters

location
Type: System::Int32%

The variable whose value is to be incremented.

Return Value

Type: System::Int32

The incremented value.

Exception Condition
NullReferenceException

The address of location is a null pointer.

This method handles an overflow condition by wrapping: if location = Int32::MaxValue, location + 1 = Int32::MinValue. 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 0 and incremented each time the random number generator returns a midpoint value until it reaches 10,000. Because three threads generate the random numbers, the Increment(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
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top
Show: