首页 > 解决方案 > 将事件 arg 发送到自定义事件处理函数

问题描述

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

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

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

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

标签: vb.netevent-handlingwebclient

解决方案


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

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


推荐阅读