1

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 ?

Philip Lee
  • 157
  • 3
  • 16

1 Answers1

1

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
FloatingKiwi
  • 4,408
  • 1
  • 17
  • 41
  • Nice tip about using a boolean flag, I hadn't thought of that. There's no sleep() property being offered for my thread. I'm creating it with Dim threadParser As Task = Nothing and then starting the thread with threadParser = Task.Factory.StartNew(Sub() Parser.Process()) Would switching to threads be better ? – Philip Lee Sep 09 '16 at 22:31
  • General rule is don't sleep on a threadpool thread. If its a short lived thing then go for it. If your thread will hang around for the life of the app then add a dedicated thread. Import system.threading to access thread.sleep – FloatingKiwi Sep 09 '16 at 22:35
  • The threads will hang around for as long as the Windows application will - ideally this will be days or even weeks so I've converted it to threads and it's running fine. Thank you very much ! – Philip Lee Sep 09 '16 at 23:05