How to: Use Components That Support the Event-based Asynchronous Pattern
Many components provide you with the option of performing their work asynchronously. The SoundPlayer and PictureBox components, for example, enable you to load sounds and images "in the background" while your main thread continues running without interruption.
Using asynchronous methods on a class that supports the Event-based Asynchronous Pattern Overview can be as simple as attaching an event handler to the component's MethodNameCompleted event, just as you would for any other event. When you call the MethodNameAsync method, your application will continue running without interruption until the MethodNameCompleted event is raised. In your event handler, you can examine the AsyncCompletedEventArgs parameter to determine if the asynchronous operation successfully completed or if it was canceled.
For more information about using event handlers, see Event Handlers Overview (Windows Forms).
The following procedure shows how to use the asynchronous image-loading capability of a PictureBox control.
To enable a PictureBox control to asynchronously load an image
Create an instance of the PictureBox component in your form.
Assign an event handler to the LoadCompleted event.
Check for any errors that may have occurred during the asynchronous download here. This is also where you check for cancellation.
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
Add two buttons, called loadButton and cancelLoadButton, to your form. Add Click event handlers to start and cancel the download.
Run your application.
As the image download proceeds, you can move the form freely, minimize it, and maximize it.