使用 DownloadDataCompleted 方法时需要将附加参数传递给事件处理程序
Need to pass additional parameter to event handler while using DownloadDataCompleted method
我需要使用WebClient.DownloadDataAsync 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
overload which takes an additional object, and then recieve it again via the 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)
我需要使用WebClient.DownloadDataAsync 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
overload which takes an additional object, and then recieve it again via the 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)