VB.net DownloadDataAsync到MemoryStream无法正常工作

问题描述 投票:0回答:1

我有以下代码将图片从互联网直接加载到我的图片框(从内存):

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"))))

它返回错误“表达式不生成值”

vb.net bitmap webclient memorystream
1个回答
1
投票

正如错误消息所述,您不能简单地将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
© www.soinside.com 2019 - 2024. All rights reserved.