i have this code that is suppose to work with at starting the minimum number of threads, say 5. when it starts the first five threads, it automatically replaces any thread that is finished making sure that there is always five threads working.
the problem here is that, am finding it difficult to manage where am suppose perform locks
Private Sub StartProcess()
intNextItemIndex = intMaxThreadCount
' start the first five threads
For i = 0 To intMaxThreadCount
If i < ListWorkItems.Count Then
StartNextItem(i)
End If
Next
' update running threads
End Sub
Private Sub StartNextItem(ByVal index As Integer)
Dim tt As New ThreadTask
If index < ListWorkItems.Count Then
' start parsing thread
Dim t As New Thread(AddressOf DoWork)
With tt
.Index = index
.Task = "count"
.Data = CStr(index * index)
End With
With t
.IsBackground = True
.Name = "Thread " & index
.Start(tt)
End With
Thread.Sleep(100)
End If
End Sub
Private Sub DoWork(ByVal data As Object)
Dim tt As ThreadTask = CType(data, ThreadTask)
Dim sTemp As String = Nothing
Dim objLock As Object = New Object()
Dim t As Double = 0
myWatch = New Stopwatch
Try
Debug.Print("Incoming index: " & CInt(tt.Index))
myWatch.Start()
SyncLock (objLock)
sTemp = PerformWork(ListWorkItems(CInt(tt.Index)).ToString)
'sTemp = CountTo()
End SyncLock
myWatch.Stop()
t = myWatch.ElapsedMilliseconds / 1000
AddItem(tt.Index, t.ToString & " = " & sTemp)
'AddItem(index, t.ToString)
Catch ex As Exception
' catch error
Debug.Print( ex.Message)
End Try
end sub
Public Sub AddItem(ByVal index As Integer, ByVal item As String)
If Me.InvokeRequired Then
Me.Invoke(New AddItemDelegate(AddressOf AddItem), index, item)
Else
Dim objLock As Object = New Object()
Dim lvItem As New ListViewItem
SyncLock (objLock)
count += 1
intNextItemIndex += 1
End SyncLock
With lvItem
.Text = index.ToString
.SubItems.Add(ListWorkItems(index).ToString)
If item.Length < 100 Then
.SubItems.Add(item.ToString)
Else
.SubItems.Add(item.Length.ToString)
End If
End With
listView1.Items.Add(lvItem)
If count = ListWorkItems.Count Then
Button1.Enabled = True
tsslStatus.Text = "Finished!!"
Debug.Print("Finished: " & index.ToString)
Else
tsslStatus.Text = "Processing item (" & count + 1 & ")"
End If
StartNextItem(intNextItemIndex)
End If
End Sub
can someone help me review it and tell me whats wrong with it?
Are the loks ok?
Is this way of doing it ok?
What possible improvements can i make
thanks all