It sounds to me that you should be using a ConcurrentQueue(Of T)
. The whole point of a queue is that you can pick the next item off the front so if you use a queue data structure then there's no incrementing of any counter required. On top of that functionality provided by the Queue(Of T)
class, the ConcurrentQueue(Of T)
class is also thread-safe. Sounds rather like exactly what you need. Just call TryDequeue
each time you want an item and it will return False
when there are no more.
Try the following in a new Console Application project to see the principle in action:
Imports System.Collections.Concurrent
Imports System.Threading
Module Module1
'A thread-safe queue containing numbers from 1 to 100.
Private numbers As New ConcurrentQueue(Of Integer)(Enumerable.Range(1, 100))
'Random number generator.
Private rng As New Random
Sub Main()
'Read the queued numbers using five threads.
For i = 1 To 5
Call New Thread(AddressOf DisplayNumbers).Start()
Next
Console.ReadLine()
End Sub
Private Sub DisplayNumbers()
Dim number As Integer
'Try to get the next number until there are no more.
Do While numbers.TryDequeue(number)
'Display the number and the thread that read it.
Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}; Number: {number}")
'Wait a random time period.
Thread.Sleep(rng.Next(500, 1000))
Loop
End Sub
End Module