0

I have the following code to load a picture from the internet directly into my picturebox (from memory):

PictureBox1.Image = New Bitmap(New IO.MemoryStream(New Net.WebClient().DownloadData("LINK")))

The problem here is that my application freezes while the WebClient is downloading, so I thought I would use DownloadDataAsync

However, using this code doesnt work at all:

PictureBox1.Image = New Bitmap(New IO.MemoryStream(New Net.WebClient().DownloadDataAsync(New Uri("LINK"))))

It returns the error "Expression does not produce a value"

2zoo
  • 47
  • 6
  • https://stackoverflow.com/questions/1585985/how-to-use-the-webclient-downloaddataasync-method-in-this-context – Steve Feb 23 '19 at 10:49
  • 1
    [PictureBox.LoadAsync](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.picturebox.loadasync). – Jimi Feb 23 '19 at 12:28

1 Answers1

1

As the error message states, you cannot simply pass the DownloadDataAsync as MemoryStream parameter, since DownloadDataAsync is a Sub whereas DownloadData is a function returning Bytes().

In order to use DownloadDataSync, check out sample code below:

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

Below are the event handlers:

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
ajakblackgoat
  • 2,119
  • 1
  • 15
  • 10