views:

87

answers:

4

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.xivio.com/avimgs/" & Username.Text & ".gif").GetResponse().GetResponseStream())
+1  A: 

You need to download the image in a background thread. See the following document for details on threads:

http://support.microsoft.com/kb/315577

0xfe
Thanks! What I did is have a load thread to see if a Boolean is true, and if it is to load the image.
Bubby4j
+5  A: 

You can use the background worker process or create a seperate thread on your own.

MSDN Link

Cody C
use ThreadPool.QueueUserWorkItem before creating a new thread on your own. http://stackoverflow.com/questions/684640/advantage-of-using-thread-start-vs-queueuserworkitem
Cheeso
Creating threads is fun, but why not just use the built-in support for asynchronous loading in the PictureBox. `PictureBox1.LoadAsync("http://www.tailspintoys.com/image.jpg") `
MarkJ
+1  A: 

Coroutines per se are not implemented in .NET. You will have to use a thread for this. I have played around a bit with fibers and .NET but there are some significant technical issues to making that work in a managed environment. This thread has some good discussion and links.

dkackman
+2  A: 

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
MarkJ