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

Home
VB.Net Tutorial
1.Language Basics
2.Data Type
3.Operator
4.Statements
5.Date Time
6.Class Module
7.Development
8.Collections
9.Generics
10.Attributes
11.Event
12.LINQ
13.Stream File
14.GUI
15.GUI Applications
16.Windows Presentation Foundation
17.2D Graphics
18.I18N Internationlization
19.Reflection
20.Regular Expressions
21.Security
22.Socket Network
23.Thread
24.Windows
25.XML
26.Database ADO.net
27.Design Patterns
VB.Net
VB.Net by API
VB.Net Tutorial » Thread » Interlocked 
23.12.1.A thread-safe way to increment and decrement an integer value
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 = 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
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.