如何:使用支持基于事件的异步模式的组件

许多组件都支持异步执行工作。 例如,通过 SoundPlayerPictureBox 组件,可以“在后台”加载音频和图像,同时主线程继续运行而不中断。

对支持基于事件的异步模式概述的类使用异步方法,这与将事件处理程序附加到组件的 MethodNameCompleted 事件一样简单,就像处理其他任何事件一样。 调用 MethodNameAsync 方法后,应用程序会继续运行而不中断,除非 MethodNameCompleted 事件抛出。 在事件处理程序中,可以检查 AsyncCompletedEventArgs 参数,以确定异步操作是已成功完成,还是已取消。

若要详细了解如何使用事件处理程序,请参阅事件处理程序概述

下面的过程展示了如何使用 PictureBox 控件的异步图像加载功能。

启用 PictureBox 控件以异步加载图像的具体步骤

  1. 在窗体中,创建 PictureBox 组件的实例。

  2. 将事件处理程序分配给 LoadCompleted 事件。

    检查是否有异步下载期间可能会发生的任何错误。 此时,还检查是否有取消事件。

    public Form1()
    {
        InitializeComponent();
    
        this.pictureBox1.LoadCompleted +=
            new System.ComponentModel.AsyncCompletedEventHandler(this.pictureBox1_LoadCompleted);
    }
    
    Friend WithEvents PictureBox1 As System.Windows.Forms.PictureBox
    
    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");
        }
    }
    
    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
    
  3. 将两个按钮 loadButtoncancelLoadButton 添加到窗体。 添加 Click 事件处理程序,以启动和取消下载。

    private void loadButton_Click(object sender, EventArgs e)
    {
        // Replace with a real url.
        pictureBox1.LoadAsync("https://unsplash.com/photos/qhixfmpqN8s/download?force=true&w=1920");
    }
    
    Private Sub loadButton_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles loadButton.Click
    
        ' Replace with a real url.
        PictureBox1.LoadAsync("https://unsplash.com/photos/qhixfmpqN8s/download?force=true&w=1920")
    
    End Sub
    
    private void cancelLoadButton_Click(object sender, EventArgs e)
    {
        pictureBox1.CancelAsync();
    }
    
    Private Sub cancelLoadButton_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles cancelLoadButton.Click
    
        PictureBox1.CancelAsync()
    
    End Sub
    
  4. 运行应用程序。

    随着图像继续下载,可以随意移动窗体,也能最小化和最大化窗体。

另请参阅