2014-09-25 70 views
0

我有一个多线程程序,从互联网下载信息从不同的代理。我有它工作正常,但我必须为每个线程添加功能,以便我知道哪个线程正在处理。所以如果我想要10个线程,我需要10个名为processItems0,processItems1,processItems2等的函数。我的processItems0函数所做的就是将数据传递给具有索引的另一个函数。我希望我可以像processItems(0)那样做一些事情,这样我就可以拥有1个函数,并且不需要一堆if语句来跟踪数据来自哪个webclient。我希望它支持100线程,如果我想要它。即将开展的工作,但它不能成为最好的方式。在此先感谢VB.net AddHandler与索引

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 

回答

0

请记住删除您的事件处理程序,以防止内存泄漏。

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 
+0

忘了提及你应该列出这些对象,并且每次添加索引时都会增加索引。 – scottyeatscode 2014-09-25 20:59:17

+0

这看起来不错...今晚去试试..谢谢 – gezzuzz 2014-09-25 21:19:16

+0

没问题,伙计。我在工作,所以我无法真正扩展它。只是爱解决问题。 ; P – scottyeatscode 2014-09-26 02:50:31