我有一个BackgroundWorker来下载图像文件并在PictureBox中查看它。我想报告下载的进度(因为它可能是一个大的图像文件(并更新ProgressBar。我似乎找不到合适的方法。
我在微软文档中找到了这篇文章,但它只包含C#的用法。有人能给我指正确的方向吗?
我在BackgroundWorker中的实际代码:
Private Sub BackgroundWorker3_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker3.DoWork
Dim Test1 As String = "DOWNLOAD URL"
Dim tClient As WebClient = New WebClient
Dim tImage As Bitmap = Bitmap.FromStream(New MemoryStream(tClient.DownloadData(Test1)))
PictureBox1.SizeMode = PictureBoxSizeMode.Zoom
PictureBox1.Image = tImage
End Sub
我想它可能有点像BackgroundWorker的ReportProgress,但我不知道如何将其应用于下载数据,因为我不知道实际的文件大小:
ReportProgress(Convert.ToInt32((contagem / count) * 100))
正如Devs在评论中所说,在异步模式下下载数据的一种有效方法可能是:有两个事件,一个用于进度,另一个在下载结束时。我整理了一些代码作为基础,你可以开始改进。希望这是你的目标:(
Event OnDownloadCompleted(downloadedDataAsByteArray() As Byte)
Event OnDownloadProgress(percentage As Integer)
Private Sub DownLoadFileAsync(address As String)
Dim client As Net.WebClient = New Net.WebClient()
AddHandler client.DownloadDataCompleted, Sub(sender As Object, e As System.Net.DownloadDataCompletedEventArgs)
RaiseEvent OnDownloadCompleted(e.Result)
End Sub
AddHandler client.DownloadProgressChanged, Sub(sender As Object, e As System.Net.DownloadProgressChangedEventArgs)
RaiseEvent OnDownloadProgress(e.ProgressPercentage)
Application.DoEvents()
End Sub
Dim uri As Uri = New Uri(address)
client.DownloadDataAsync(uri)
End Sub
使用
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddHandler Me.OnDownloadProgress, Sub(percet As Integer)
Console.WriteLine("Percent reiceved: " & percet.ToString)
End Sub
AddHandler Me.OnDownloadCompleted, Sub(data() As Byte)
Console.WriteLine("Download completed, total: " & data.Count)
Using mStream As New MemoryStream(data)
'Do what you want with this image
Dim image As Image = Image.FromStream(mStream)
End Using
End Sub
DownLoadFileAsync("https://images.pexels.com/photos/3952233/pexels-photo-3952233.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260")
End Sub