Search code examples
vb.netmultithreadingconcurrent-queue

VB.Net: Retrieving items from a ConcurrentQueue on a thread


I've got a class running on one thread which listens for data and pushes it into a ConcurrentQueue of strings. I'm adding data to it using Enqueue and I can see that the queue length is growing so I know that data is being queue correctly.

Another class running on another thread should then take each piece of data out on a FIFO basis. However, it simply does nothing. Here's the loop that should pull the data out of the queue:

Dim data As String = Nothing

While Globals.queueMessages.Count > 0

    queueMessages.TryDequeue(data)
    If (data IsNot Nothing) Then
        Console.WriteLine(data)
    Else
        Console.WriteLine("Failed to dequeue")
    End If
End While

As well as checking the number of items in the queue using Count() I've also tried IsEmpty too. Same result !?

Whilst there seems to be quite a few articles about using ConcurrentQueue in C#, I've not found any VB.Net examples so I'm a bit stuck.

Help !

UPDATE: Wrapping my While ... End While in a Do ... Loop does work but then ties up the thread when nothing is happening so it's probably not recommended. Is there a more elegant way to do this ?


Solution

  • As you found out, you need to loop continuously as the queue is allowed to be empty and you don't want the loop to drop out. Just sleep for a small interval to allow it to be refilled. A simple boolean flag for controlling when your operation is done is all thats required for terminating.

        Dim data As String = Nothing
    
        While mCancel = False
    
            If queueMessages.TryDequeue(data) Then
                Console.WriteLine(data)
            Else
                Console.WriteLine("Empty")
                Thread.sleep(50)
            End If
    
        End While