dimanche 10 mai 2015

VB.Net is there a better way than SyncLock to increment a counter?

kind of a beginner-intermediate so sorry if this is a noob question...but I would like to know if there is a better way than the following code to increment a counter in a subroutine that is ran by multiple threads. Also, if there is, what are the differences between using SyncLock with a lock object and the alternative?

Imports System.Threading

Public Class AccountCreator

    Public Property Accounts As List(Of IAccount)
    Public Property ThreadCount As Integer = 50
    Public Property Threads As List(Of Thread)

    Private accountIndex As Integer
    Private lockObject As Object

    Public Sub CreateAccounts()
        lockObject = New Object
        Threads = New List(Of Thread)
        For i = 0 To ThreadCount - 1
            Dim t As New Thread(AddressOf ThreadProc)
            Me.Threads.Add(t)
            t.Start()
        Next

    End Sub

    Private Sub ThreadProc()
        Dim account As IAccount = Accounts(accountIndex)
        account.CreateAccount()
        SyncLock lockObject
            accountIndex += 1
        End SyncLock
        If accountIndex = Accounts.Count Then
            'No more accounts to process.
            Exit Sub
        End If
        'Recursive call.
        ThreadProc()
    End Sub


End Class

Aucun commentaire:

Enregistrer un commentaire