Interlocked::Decrement Method (Int32%)
Decrements a specified variable and stores the result, as an atomic operation.
Assembly: mscorlib (in mscorlib.dll)
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 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.
The following example is similar to the previous one, except that it uses the task-based asynchronous pattern 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.
.NET FrameworkSupported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1
.NET Framework Client ProfileSupported in: 4, 3.5 SP1
XNA FrameworkSupported in: 3.0, 2.0, 1.0
Portable Class LibrarySupported in: Portable Class Library
Supported in: Windows Phone 8.1
Supported in: Windows Phone Silverlight 8.1
Supported in: Windows Phone Silverlight 8