Tuesday, April 24, 2012


Thread Safety in VB.Net


Dim iThread As Integer
Dim manualEvents(4) As ManualResetEvent
Sub Main()
    For i = 0 To 4
        manualEvents(i) = New ManualResetEvent(False)
        ThreadPool.QueueUserWorkItem(AddressOf DoOne)
    Next

    For Each handle As WaitHandle In manualEvents
        handle.WaitOne()
    Next

    ' do other stuff
EndSub

Private Shared lockObject As New Object()
Private Sub DoOne()
  SyncLock (lockObject)
    If QueryQueue.DoOne() Then
        DoOne()
    Else
        manualEvents(iThread).Set()
        iThread = iThread + 1
    End If
  End SyncLock
End Sub

No comments:

Post a Comment