将事件arg发送到自定义事件处理函数

问题描述

我有一个初始化Webclient对象的类,该类具有DownloadProgressChangedDownloadFileCompleted事件。表单可以启动此对象和下载。如果用户选择关闭表单,则表单也可以停止下载。

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_complete Sub的内容类似于:

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事件处理程序。在该事件处理程序中,您可以使用我在博客文章中概述的步骤,使用所需信息引发自己的自定义事件。