1

我正在创建一个程序来从下载网站下载文件。我创建了一个后台工作程序来处理下载大文件,因为它通常在下载大文件时冻结 UI。

我已经设法让它工作,但我现在面临的问题是我无法使用我的 AddHandler 来显示更改的进度,所以我尝试使用调用方法来更改进度值。

这是我为调用方法尝试的代码:

Dim ProgressChanged As New ProgressChange(AddressOf bw_ProgressChanged)
Me.Invoke(ProgressChanged, Nothing, EventArgs.Empty)

这是我的 ProgressChanged 处理程序。

Private Sub bw_ProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
    Dim bytesIn As Double = Double.Parse(e.BytesReceived.ToString())
    Dim totalBytes As Double = Double.Parse(e.TotalBytesToReceive.ToString())
    Dim percentage As Double = bytesIn / totalBytes * 100
    ProgressBarCurrent.Value = Int32.Parse(Math.Truncate(percentage).ToString())

    Dim BytesDownloaded As String = (e.BytesReceived / (DirectCast(e.UserState, Stopwatch).ElapsedMilliseconds / 1000.0#)).ToString("#")

    If BytesDownloaded < 1024 Then
        Dim Bs As String = Convert.ToInt32(BytesDownloaded)
        Label4.Text = (Bs & " B/s")
    ElseIf BytesDownloaded < 1048576 Then
        Dim KBs As String = Math.Round(BytesDownloaded / 1024, 2)
        Label4.Text = (KBs & " KB/s")
    ElseIf BytesDownloaded < 1073741824 Then
        Dim MBs As String = Math.Round(BytesDownloaded / 1048576, 2)
        Label4.Text = (MBs & " MB/s")
    ElseIf BytesDownloaded < 1099511627776 Then
        Dim GBs As String = Math.Round(BytesDownloaded / 1073741824, 2)
        Label4.Text = (GBs & " GB/s")
    Else
        Label4.Text = ("Estimating...")
    End If
End Sub

它有更多代码,但我认为没有必要展示。

这是我的代表潜艇。

Delegate Sub ProgressChange(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)

我还用 addhandler 方法尝试了一些不同的东西。

AddHandler wc.DownloadProgressChanged, AddressOf bw_ProgressChanged

在我使用此代码之前,我遇到了一个错误,但现在当我使用它时,没有错误,但代码实际上并没有做任何事情,就像它甚至没有被触发一样,所以我认为添加处理程序不起作用。

我不确定是否可以对 DownloadProgressChanged 使用 Invoke 方法,但我相信应该可以,而且我不确定我会使用什么参数。我尝试了不同的论点,我认为这些论点会奏效,但没有奏效。

4

1 回答 1

0

You need to call [YourBackgroundWorkerObject].ReportProgress from inside DoWork. This triggers the ProgressChanged event.
Your ProgressChanged-procedure must then invoke the method that does the UI changes.
(BTW, you can as well skip that Progress-Reporting-Reroute of the BGW. Invoke your own UI-changing method directly from DoWork.)

于 2013-08-18T16:06:58.417 回答