Search code examples
vb.netproducer-consumerblockingcollection

Basic BlockingCollection Producer Consumer in VB.NET


I have been struggling for the last few hours to get a basic implementation of BlockingCollection to work. I cannot seem to find a tutorial in VB.NET for the life of me, so have been trying to get something working from tutorials in C#.

I just want to get a basic implementation working so I can progress to doing what I actually need. But I am stuck.

This is my code currently:

Dim blockingCollection As BlockingCollection(Of String) = New BlockingCollection(Of String)
        Dim count As Integer = 0

        Task.Factory.StartNew(Sub()
                                  While (True)
                                      blockingCollection.Add("value" + count)
                                      count = count + 1
                                  End While
                              End Sub)

        Task.Factory.StartNew(Sub()
                                  For Each value As String In blockingCollection.GetConsumingEnumerable()
                                      Debug.Print("Worker 1: " + value)
                                  Next
                              End Sub)

I get no output from running this, just the following exceptions:

A first chance exception of type 'System.FormatException' occurred in mscorlib.dll A first chance exception of type 'System.FormatException' occurred in Microsoft.VisualBasic.dll A first chance exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll

I have been googling persistently for the past few hours to try and resolve this, but to no avail. Hopefully someone here can help.

Thanks


Solution

  • This code executes, though I don't know what it is that you want.

        Dim blockingCollection As BlockingCollection(Of String) = New BlockingCollection(Of String)
        Dim count As Integer = 0
    
        Task.Factory.StartNew(Sub()
                                  While True
                                      blockingCollection.Add("value" & count.ToString)
                                      count = count + 1
                                  End While
                              End Sub)
    
        Task.Factory.StartNew(Sub()
                                  For Each value As String In blockingCollection.GetConsumingEnumerable()
                                      Debug.WriteLine("Worker 1: " & value)
                                  Next
                              End Sub)