Increment Method (Int32)
.NET Framework Class Library
Interlocked..::.Increment Method (Int32%)

Updated: February 2009

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

Namespace:  System.Threading
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic (Declaration)
Public Shared Function Increment ( _
    ByRef location As Integer _
) As Integer
Visual Basic (Usage)
Dim location As Integer
Dim returnValue As Integer

returnValue = Interlocked.Increment(location)
C#
public static int Increment(
    ref int location
)
Visual C++
public:
static int Increment(
    int% location
)
JScript
public static function Increment(
    location : int
) : int

Parameters

location
Type: System..::.Int32%
The variable whose value is to be incremented.

Return Value

Type: System..::.Int32
The incremented value.
ExceptionCondition
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 code example shows a thread-safe way to increment and decrement an integer value. SafeInstanceCount will always be zero. However, UnsafeInstanceCount will not necessarily be zero because a race condition occurs between incrementing and decrementing the count. This effect is especially marked on a multiprocessor computer.

Visual Basic
Imports Microsoft.VisualBasic
Imports System
Imports System.Threading

Public Class Test

    <MTAThread> _
    Shared Sub Main()
        Dim thread1 As New Thread(AddressOf ThreadMethod)
        Dim thread2 As New Thread(AddressOf ThreadMethod)
        thread1.Start()
        thread2.Start()
        thread1.Join()
        thread2.Join()

        ' Have the garbage collector run the finalizer for each
        ' instance of CountClass and wait for it to finish.
        GC.Collect()
        GC.WaitForPendingFinalizers()

        Console.WriteLine("UnsafeInstanceCount: {0}" & _
            vbCrLf & "SafeCountInstances: {1}", _
            CountClass.UnsafeInstanceCount.ToString(), _
            CountClass.SafeInstanceCount.ToString())
   End Sub

   Shared Sub ThreadMethod()
        Dim cClass As CountClass 

        ' Create 100,000 instances of CountClass.
        For i As Integer = 1 To 100000
            cClass = New CountClass()
        Next i
   End Sub

End Class

Public Class CountClass

    Shared unsafeCount As Integer = 0
    Shared   safeCount As Integer = 0

    Shared ReadOnly Property UnsafeInstanceCount As Integer
        Get
            Return unsafeCount
        End Get
    End Property

    Shared ReadOnly Property SafeInstanceCount As Integer
        Get
            Return safeCount
        End Get
    End Property

    Sub New()
        unsafeCount += 1
        Interlocked.Increment(safeCount)
    End Sub

    Protected Overrides Sub Finalize()
        unsafeCount -= 1
        Interlocked.Decrement(safeCount)
        MyBase.Finalize()
    End Sub

End Class
C#
using System;
using System.Threading;

class Test
{
    static void Main()
    {
        Thread thread1 = new Thread(new ThreadStart(ThreadMethod));
        Thread thread2 = new Thread(new ThreadStart(ThreadMethod));
        thread1.Start();
        thread2.Start();
        thread1.Join();
        thread2.Join();

        // Have the garbage collector run the finalizer for each
        // instance of CountClass and wait for it to finish.
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("UnsafeInstanceCount: {0}" +
            "\nSafeCountInstances: {1}",
            CountClass.UnsafeInstanceCount.ToString(),
            CountClass.SafeInstanceCount.ToString());
    }

    static void ThreadMethod()
    {
        CountClass cClass;

        // Create 100,000 instances of CountClass.
        for(int i = 0; i < 100000; i++)
        {
            cClass = new CountClass();
        }
    }
}

class CountClass
{
    static int unsafeInstanceCount = 0;
    static int   safeInstanceCount = 0;

    static public int UnsafeInstanceCount
    {
        get {return unsafeInstanceCount;}
    }

    static public int SafeInstanceCount
    {
        get {return safeInstanceCount;}
    }

    public CountClass()
    {
        unsafeInstanceCount++;
        Interlocked.Increment(ref safeInstanceCount);
    }

    ~CountClass()
    {
        unsafeInstanceCount--;
        Interlocked.Decrement(ref safeInstanceCount);
    }
}
Visual C++
using namespace System;
using namespace System::Threading;
ref class CountClass
{
private:
   static int unsafeInstanceCount;
   static int safeInstanceCount;

public:

   static property int UnsafeInstanceCount 
   {
      int get()
      {
         return unsafeInstanceCount;
      }

   }

   static property int SafeInstanceCount 
   {
      int get()
      {
         return safeInstanceCount;
      }

   }
   CountClass()
   {
      unsafeInstanceCount++;
      Interlocked::Increment( safeInstanceCount );
   }

   // Destructor and finalizer. The finalizer is used to decrement the
   // count, so garbage collection enforces decrementing.
   ~CountClass() { this->!CountClass(); }
   !CountClass()
   {
      unsafeInstanceCount--;
      Interlocked::Decrement( safeInstanceCount );
   }
};

ref class Test
{
public:
   static void ThreadMethod()
   {
      CountClass^ cClass;

      // Create 100,000 instances of CountClass.
      for ( int i = 0; i < 100000; i++ )
      {
         cClass = gcnew CountClass;
      }
   }

};

int main()
{
   Thread^ thread1 = gcnew Thread( gcnew ThreadStart( &Test::ThreadMethod ) );
   Thread^ thread2 = gcnew Thread( gcnew ThreadStart( &Test::ThreadMethod ) );
   thread1->Start();
   thread2->Start();
   thread1->Join();
   thread2->Join();

   // Have the garbage collector run the finalizer for each
   // instance of CountClass and wait for it to finish.
   GC::Collect();
   GC::WaitForPendingFinalizers();
   Console::WriteLine( "UnsafeInstanceCount: {0}"
   "\nSafeCountInstances: {1}", CountClass::UnsafeInstanceCount.ToString(), CountClass::SafeInstanceCount.ToString() );
}

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0

Date

History

Reason

February 2009

Fixed code bugs in the Visual Basic example: the code was double-incrementing i and unnecessarily setting cClass to Nothing.

Customer feedback.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Could CountClass.SafeInstanceCount() return a stale value?      davidofmorris   |   Edit   |   Show History

I'm a little concerned about the example here. Shouldn't CountClass's static method SafeInstanceCount() return Interlocked.Read(ref safeInstanceCount)? Otherwise, while the actual value of safeInstanceCount may be consistent (zero - after all instances have been finalized by the garbage collector,) the main thread may not see the latest value.

Could this specific issue be solved by making safeInstanceCount volatile (as well as using the Interlocked methods?)

Processing
Page view tracker