正在将事件arg发送到自定义事件处理程序函数



我有一个类,它启动一个web客户端对象,并具有一个DownloadProgressChanged和一个DownloadFileCompleted事件。表单可以启动此对象和下载。如果用户选择关闭表单,表单也可以停止下载。

DownloadFileCompleted事件处理程序函数还接受一个参数filename来引发事件,然后表单类可以处理该事件。我阅读了如何定义这样的自定义处理程序函数,因此我的代码如下所示:

AddHandler fileReader.DownloadFileCompleted, Sub(sender, e) download_complete(FileName)
AddHandler fileReader.DownloadProgressChanged, AddressOf Download_ProgressChanged
fileReader.DownloadFileAsync(New Uri(Address), ParentPath + FileName)
Private Sub download_complete(filename As String)
RaiseEvent DownloadDone(filename)

End Sub

我注意到,当用户关闭表单时,下载会停止,但我仍然会收到下载完成事件(我读到e.Cancelled = True会附带此事件(

我的问题是,当我引发的事件时,我想发送这些信息,所以我的download_completeSub会读到这样的内容:

Private Sub download_complete(filename As String, e as AsyncCompletedEventArgs)
If e.Cancelled = True Then
RaiseEvent DownloadDone(filename, "CANCELLED")
Else
RaiseEvent DownloadDone(filename, "COMPLETE")
End If

End Sub

这样,我就可以在表单的事件处理程序方法中很好地处理以下过程。我找不到该方法的任何文档。有人能帮帮我吗?

如果我正确理解你,这就是你需要做的事情:

Imports System.ComponentModel
Imports System.Net
Public Class Form1
Public Event DownloadComplete As EventHandler(Of DownloadCompleteEventArgs)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim downloader As New WebClient
AddHandler downloader.DownloadFileCompleted, AddressOf downloader_DownloadFileCompleted
Dim sourceUri As New Uri("source address here")
Dim destinationPath = "destination path here"
downloader.DownloadFileAsync(sourceUri, destinationPath, destinationPath)
End Sub
Private Sub downloader_DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs)
Dim downloader = DirectCast(sender, WebClient)
RemoveHandler downloader.DownloadFileCompleted, AddressOf downloader_DownloadFileCompleted
Dim filePath = CStr(e.UserState)
OnDownloadComplete(New DownloadCompleteEventArgs(filePath, e.Cancelled))
End Sub
Protected Overridable Sub OnDownloadComplete(e As DownloadCompleteEventArgs)
RaiseEvent DownloadComplete(Me, e)
End Sub
End Class
Public Class DownloadCompleteEventArgs
Inherits EventArgs
Public ReadOnly Property FilePath As String
Public ReadOnly Property IsCancelled As Boolean
Public Sub New(filePath As String, isCancelled As Boolean)
Me.FilePath = filePath
Me.IsCancelled = isCancelled
End Sub
End Class

首先调用DownloadFileAsync的重载,该重载允许您在中传递数据,然后返回DownloadFileCompleted事件处理程序。在该事件处理程序中,您可以使用我在博客文章中概述的步骤,用您想要的信息引发您自己的自定义事件。

最新更新