A thread-safe way to increment and decrement an integer value : Interlocked « Thread « VB.Net Tutorial






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()

        GC.Collect()
        GC.WaitForPendingFinalizers()

        Console.WriteLine(CountClass.UnsafeInstanceCount.ToString())
        Console.WriteLine(CountClass.SafeInstanceCount.ToString())
   End Sub

   Shared Sub ThreadMethod()
        Dim cClass As 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








23.12.Interlocked
23.12.1.A thread-safe way to increment and decrement an integer value