Question Multiple Threads 1 Job

Tyron199

Member
Joined
Apr 16, 2009
Messages
9
Programming Experience
3-5
Hey, I am trying to have multiple threads run through an arraylist of object and process each object. My problem is that each thread processes every object in the array.So they are not working together on the job. I made sample application to show my problem. I think the problem is somewhere in my ThreadSub() Here is the code:

VB.NET:
Imports System.Threading
Public Class Form1
    Dim myitems As New ArrayList

    Structure MyItem
        Public name
        Public id
        Public processed As Boolean
    End Structure

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For c = 0 To 500
            Dim thisobj As New MyItem
            thisobj.id = c.ToString
            thisobj.name = DateTime.Now.ToString
            thisobj.processed = False
            myitems.Add(thisobj)
        Next
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        For c = 0 To 2
            Dim thisthread As New Thread(AddressOf ThreadSub)
            thisthread.Name = "Thread:" + c.ToString
            thisthread.Start()
        Next
    End Sub

    Sub ThreadSub()

        For Each itm As MyItem In myitems        
            If itm.processed = False Then
                itm.processed = True
                AddtoList(Thread.CurrentThread.Name + " object: " + itm.name + " id " + itm.id)
            End If

        Next

    End Sub

    Sub AddtoList(ByVal text As String)
        If Me.ListBox1.InvokeRequired Then
            Dim d As New ContextCallback(AddressOf AddtoList)
            Me.Invoke(d, New Object() {text})
        Else
            ListBox1.Items.Add(text)
            ListBox1.SelectedIndex = ListBox1.Items.Count - 1
        End If
    End Sub

End Class
 
You can change Structure MyItem to Class MyItem and it will do what you intended. Why? A Structure is a value type, when you get an item from the array with the For Each loop you get a value that has no reference back to the array, it's just a copy of the value and changes of this value is not read by the other threads.

Alternative to making the items class reference types is to access the array by integer, and then reassigns the new array value. You'd have to sync access to the list as an atomic operation.
 
I always found it more logical to have a Queue, and to remove an item from it, then process the item. If you need to keep it, push it into a done Queue when youre done with it
 
Back
Top