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

  1. Create an instance of the PictureBox component in your form.

  2. 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.

    public Form1()
    {
        InitializeComponent();
    
        this.pictureBox1.LoadCompleted += 
            new System.ComponentModel.AsyncCompletedEventHandler(this.pictureBox1_LoadCompleted);
    }
    
    private void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            MessageBox.Show(e.Error.Message, "Load Error");
        }
        else if (e.Cancelled)
        {
            MessageBox.Show("Load canceled", "Canceled");
        }
        else
        {
            MessageBox.Show("Load completed", "Completed");
        }
    }
    
  3. Add two buttons, called loadButton and cancelLoadButton, to your form. Add Click event handlers to start and cancel the download.

    private void loadButton_Click(object sender, EventArgs e)
    {
        // Replace with a real url.
        pictureBox1.LoadAsync("http://www.tailspintoys.com/image.jpg");
    }
    
    private void cancelLoadButton_Click(object sender, EventArgs e)
    {
        pictureBox1.CancelAsync();
    }
    
  4. Run your application.

    As the image download proceeds, you can move the form freely, minimize it, and maximize it.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft