我有一个多线程程序,可以从互联网上下载不同代理的信息。我有它工作正常但我必须为每个线程添加函数,以便我知道正在处理哪个线程。所以,如果我想要10个线程,我需要10个名为processItems0 processItems1 processItems2的函数,依此类推。我的所有processItems0函数都将数据传递给另一个带索引的函数。我希望我可以做一些像processItems(0)这样的事情,这样我就可以拥有1个函数,并且不需要一堆if语句来跟踪数据来自哪个webclient。我希望它支持100线程,如果我想要它。什么即时工作,但它不是最好的方式。提前致谢
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 :(得分: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