我需要通过使用WebClient实现异步下载。downloaddatasync Method
我定义的事件处理程序如下:
Private Sub DownloadCompleted(sender As Object, e As DownloadDataCompletedEventArgs)
Dim bytes() As Byte = e.Result
'do somthing with result
End Sub
但是我需要向这个事件处理程序传递一个额外的参数,连同下载的结果,我创建URI的值。例如:
Dim pictureURI = "http://images.server.sample.com/" + myUniqueUserIdentifier
我需要在DownloadCompleted
子中获得myUniqueUserIdentifier
回调。
我正在使用以下代码注册我的事件处理程序:
AddHandler webClient.DownloadDataCompleted, AddressOf DownloadCompleted
我只有一个猜测,扩展WebClient
对象和覆盖DownloadDataCompleted
对象。但在我执行这个之前我想检查一下有没有更简单的解?
谢谢。
你可以使用WebClient.DownloadDataAsync
重载,它接受一个额外的对象,然后通过AsyncCompletedEventArgs.UserState
属性再次接收它。
下面是一个例子:
Sub Main
Dim url = "http://google.com"
Dim client = new WebClient()
AddHandler client.DownloadDataCompleted, AddressOf DownloadDataCompleted
client.DownloadDataAsync(new Uri(url), url) ' <- pass url as additional information...'
End Sub
Sub DownloadDataCompleted(sender as object, e as DownloadDataCompletedEventArgs)
Dim raw as byte() = e.Result
' ... and recieve it in the event handler via the UserState property'
Console.WriteLine(raw.Length & " bytes received from " & e.UserState.ToString())
End Sub
您可以使用函数来传递参数,而不是AddressOf
AddHandler webClient.DownloadDataCompleted, Function(sender, e) DownloadCompleted(param)