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