0

I have a multithread program that download info from the internet off different proxies. I have it working fine but I have to add functions for each thread so that I know which thread is being processed. so if I want 10 thread I need 10 functions named processItems0 processItems1 processItems2 and so on. All my processItems0 function does is pass the data to another function with a index. I wish I could do something thing like processItems(0) so that I can have 1 function and didn't need a stack of if statements to track which webclient the data is coming from. I want it to support 100 thread if i wanted it to. what im doing works but it cant be the best way. Thanks in advance

Dim wc As New WebClient
''' if statements that i want to get rid of
If wcn = 0 Then
    AddHandler wc.UploadStringCompleted, AddressOf processItems0
ElseIf wcn = 1 Then
    AddHandler wc.UploadStringCompleted, AddressOf processItems1
end if

wc.Proxy = wp(wcn)

Dim u As New Uri(laurl)
wc.UploadStringAsync(u, data)


''' individual functions for each webclient i want to run.. t
Private Sub processItems0(ByVal sender As Object, ByVal e As UploadStringCompletedEventArgs)
    If e.Cancelled = False AndAlso e.Error Is Nothing Then
        processData(CStr(e.Result), 0)
    End If
End Sub


Private Sub processItems1(ByVal sender As Object, ByVal e As UploadStringCompletedEventArgs)
    If e.Cancelled = False AndAlso e.Error Is Nothing Then
        processData(CStr(e.Result), 1)
    End If
End Sub

Private Sub processData(data As String, wcn As Integer)
     'process data
end Sub
Steve
  • 213,761
  • 22
  • 232
  • 286
gezzuzz
  • 188
  • 2
  • 16

1 Answers1

0

Please remember to remove your event handlers to prevent memory leaks.

Public Class ProxyWrapper 
    Inherits WebClient

    Private _index As Integer

    Public Sub New(ByVal index As Integer)
        _index = index
    End Sub

    Public ReadOnly Property Index As Integer 
        Get
            Return _index
        End Get
    End Property

    Public Sub RegisterEvent()
        AddHandler Me.UploadStringCompleted, AddressOf processItems
    End Sub

    Public Sub UnregisterEvent()
        RemoveHandler Me.UploadStringCompleted, AddressOf processItems
    End Sub

    Private Sub ProcessItems(ByVal sender As Object, ByVal e As UploadStringCompletedEventArgs)
        If e.Cancelled = False AndAlso e.Error Is Nothing Then
            ProcessData(CStr(e.Result), _index)
        End If
    End Sub

    Private Sub ProcessData(ByVal res As String, ByVal index As Integer)
        ' Handle data
    End Sub

End Class
scottyeatscode
  • 606
  • 3
  • 11