我有以下代码将图片从互联网直接加载到我的图片框(从内存):
PictureBox1.Image = New Bitmap(New IO.MemoryStream(New Net.WebClient().DownloadData("LINK")))
这里的问题是我的应用程序在WebClient下载时冻结,所以我想我会使用DownloadDataAsync
但是,使用此代码根本不起作用:
PictureBox1.Image = New Bitmap(New IO.MemoryStream(New Net.WebClient().DownloadDataAsync(New Uri("LINK"))))
它返回错误“表达式不生成值”
正如错误消息所述,您不能简单地将DownloadDataAsync
作为MemoryStream
参数传递,因为DownloadDataAsync
是Sub而DownloadData
是返回Bytes()
的函数。
要使用DownloadDataSync
,请查看以下示例代码:
Dim wc As New Net.WebClient()
AddHandler wc.DownloadDataCompleted, AddressOf DownloadDataCompleted
AddHandler wc.DownloadProgressChanged, AddressOf DownloadProgressChanged ' in case you want to monitor download progress
wc.DownloadDataAsync(New uri("link"))
以下是事件处理程序:
Sub DownloadDataCompleted(sender As Object, e As DownloadDataCompletedEventArgs)
' If the request was not canceled and did not throw
' an exception, display the resource.
If e.Cancelled = False AndAlso e.Error Is Nothing Then
PictureBox1.Image = New Bitmap(New IO.MemoryStream(e.Result))
End If
End Sub
Sub DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs)
' show progress using :
' Percent = e.ProgressPercentage
' Text = $"{e.BytesReceived} of {e.TotalBytesToReceive}"
End Sub