我需要使用WebClient.DownloadDataAsync 方法来实现异步下载
我已经定义了事件处理程序如下:
Private Sub DownloadCompleted(sender As Object, e As DownloadDataCompletedEventArgs)
Dim bytes() As Byte = e.Result
'do somthing with result
End Sub
Run Code Online (Sandbox Code Playgroud)
但是我需要向这个事件处理程序传递一个额外的参数以及我创建 URI 的下载结果值。例如:
Dim pictureURI = "http://images.server.sample.com/" + myUniqueUserIdentifier
我需要myUniqueUserIdentifier在DownloadCompletedsub 中进行回调。
我正在使用以下代码注册我的事件处理程序:
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
Run Code Online (Sandbox Code Playgroud)