.net - WebClient.DownloadData 进度报告
问题描述
我有一个 BackgroundWorker 来下载图像文件并在 PictureBox 中查看它。我想报告该下载的进度(因为它可能是一个大图像文件)并更新一个 ProgressBar。看来我找不到合适的方法来做到这一点。
我在 Microsoft 文档中找到了这篇文章,但它只包含 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))
解决方案
正如开发人员在评论中所说,以异步模式下载数据的一种有效方法可能是这样的:有两个事件,一个用于进度,另一个用于下载结束。我整理了一些代码作为您可以开始改进的基础。希望这是你的目标:)
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
推荐阅读
- php - 为什么更新会在数据库中产生这个结果` {"email":"try@gmail.com"}`
- reactjs - Formik TypeError:无法读取未定义的属性“submitForm”
- server - io.netty.channel.connecttimeoutexception 连接超时
- angular -
不附加 到 cdk-overlay-container - c++ - LLVM KaleidoscopeJIT:如何查看错误?
- kubernetes - 尝试将加密的 AWS EFS 与 EKS 中的 efs-csi-node 连接时出现挂载错误
- sql - 在 SQL Server 中将单个值与逗号分隔值进行比较
- python - 从字符串值创建唯一的短 ID
- python - 如何使用 GnuPG (gpg) 可执行文件和依赖项 (PyInstaller) 冻结 python 应用程序
- c# - UWP 相当于 Android 的 SpannableString,内部带有图像