Help with Queue and Multi-Threading (VB.net)

mixing

Regular Member
Joined
Jan 18, 2014
Messages
412
Reaction score
63
Hey everyone, I really hope someone can help me since I've been struggling to get this. Here's what I'm trying to do..

I have a list of items that I want to put into a queue and then process using either multiple threads or actions. Once I've processed the item I then want to add it along with its result into a ListView. I obviously do not want to get duplicates or have items be skipped.

Below is some of the code I've been messing with. I've struggled to get a thread pool working and found an example using ConcurrentQueue and Action via Microsoft, so that's what I've included. This works, but the results contain duplicates and even some missing data.. Any help would be really appreciated!

Code:
Private Sub btnStart_Click(sender As System.Object, e As System.EventArgs) Handles btnStart.Click
            'create and add to queue
            Dim cq As New ConcurrentQueue(Of String)()

            For Each s As String In mainlist
                cq.Enqueue(s)
            Next
            lblTotalCnt.Text = cq.Count

            'Action to consume the ConcurrentQueue
            Dim action As Action =
          Sub()
              For Each item As String In cq
                  While cq.TryDequeue(item)
                      'Processing item and adding it to ListView here
                      Try
                          testString = item
                          If PerformCheck(testString) = True Then
                              Dim str(2) As String
                              Dim itm As ListViewItem
                              str(0) = testString
                              str(1) = testUpdated

                              itm = New ListViewItem(str)

                              lstDetails.Items.Add(itm)
                              lblAnalyzedCnt.Text = lblAnalyzedCnt.Text + 1
                          Else
                              lblErrorsCnt.Text = lblErrorsCnt.Text + 1
                          End If
                      Catch ex As Exception
                          'Handle exception here
                      End Try
                  End While
              Next
          End Sub

            'Start 4 concurrent consuming actions
            Parallel.Invoke(action, action, action, action)
End Sub
 
Back
Top