Link to home
Start Free TrialLog in
Avatar of bryanpilger
bryanpilgerFlag for United States of America

asked on

How to create and use multiple background workers from a for loop

Anybody have any ideas on how to create multiple background workers based on the amount of items a for loop picks up in a listview? See code snippet for example
for each i as listviewitem in listview.items
(What do i do hear?)
next

Private Sub bgw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgw.DoWork
  Ping(IP)
End Sub

Function Ping(ByRef IP As String) As Boolean
        Try
            Return My.Computer.Network.Ping(IP)
        Catch ex As Exception
            Return False
        End Try
        Return Nothing
    End Function

Open in new window

Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Try

for each i as listviewitem in listview.items
     Dim BGW As New BackGroundWorker
     AddHandler BGW.DoWork, AddressOf(bgw_DoWork)
     BGW.RunWorkerAsync()
next
Avatar of bryanpilger

ASKER

I add that in and it gives an error under the AddressOf(bgw_DoWork()) part. Error says: Argument not specified for parameter 'e' of 'Private Sub bgw_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs)'.

Also, how am i going to pass the variable i to the background Worker? because i will replace IP in the Ping function.
ASKER CERTIFIED SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I got it. you were correct. I removed the parenthesis, and then i also had to remove the 'handles me.dowork' on the background workers that it was creating. Thanks a lot for the assistance. below is the final code:

    Private Sub bgw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgw.DoWork
        Dim counter As Integer = 0
        For Each i As ListViewItem In lvFriends.Items
            i.UseItemStyleForSubItems = False
            Dim item As New ListViewItem.ListViewSubItem
            item.Text = "Loading"
            item.Font = New System.Drawing.Font("Times New Roman", 9, FontStyle.Bold)
            item.ForeColor = Color.Blue
            i.SubItems.Add(item)
            counter += 1
        Next
        ReDim arrStatus(counter - 1)
        For i As Integer = 0 To UBound(arrStatus)
            Dim bgwFriendsUpdate As New BackgroundWorker
            AddHandler bgwFriendsUpdate.DoWork, AddressOf bgwFriendsUpdate_DoWork
            bgwFriendsUpdate.RunWorkerAsync(lvFriends.Items.Item(i))
        Next
    End Sub

    Private Sub bgwFriendsUpdate_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)

(Do my work)

    End Sub
Glad to help :-)