James T James T - 1 month ago 13
Vb.net Question

Is there a "coroutine" feature in VB?

I'm programming a application and am wondering, is there a co-routine (or something similar) feature in VB?

In my application it pulls a picture from the internet and it takes quite a long time (30-45 seconds) and it stops all code from running while it does that. Here is the line of codes that pulls that picture:

PictureBox1.Image = Image.FromStream(System.Net.HttpWebRequest.Create("http://www.example.com/avimgs/" & Username.Text & ".gif").GetResponse().GetResponseStream())

Answer

The general-purpose method is to create a background thread yourself, as in other answers.

But many .NET components provide a built-in solution for performing their work asynchronously - always easier than manually creating threads. And the PictureBox has support for asynchronous loading of images.

Here is the complete code from the MSDN sample, including error handling, cancelling the download and notification of completion. It couldn't be easier.

Private Sub loadButton_Click( _
    ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
    Handles loadButton.Click

    PictureBox1.LoadAsync("http://www.tailspintoys.com/image.jpg")

End Sub

Private Sub cancelLoadButton_Click( _
    ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
    Handles cancelLoadButton.Click

    PictureBox1.CancelAsync()

End Sub

Private Sub PictureBox1_LoadCompleted( _
    ByVal sender As System.Object, _
    ByVal e As System.ComponentModel.AsyncCompletedEventArgs) _
    Handles PictureBox1.LoadCompleted

    If (e.Error IsNot Nothing) Then
        MessageBox.Show(e.Error.Message, "Load Error")
    ElseIf e.Cancelled Then
        MessageBox.Show("Load cancelled", "Canceled")
    Else
        MessageBox.Show("Load completed", "Completed")
    End If

End Sub
Comments