返回介绍

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

发布于 2025-02-23 23:15:47 字数 2882 浏览 0 评论 0 收藏 0

许多组件都为你提供了以异步方式执行其工作的选项。 SoundPlayer 和 PictureBox 组件,例如,启用可加载听起来和图像"在后台",同时主线程继续运行而不中断。

支持的类上使用异步方法 基于事件的异步模式概述 可以很简单,例如将事件处理程序附加到组件的MethodName Completed 事件,正如你的任何其他事件一样。 当调用MethodName Async 方法,你的应用程序将继续运行而不会中断,直到MethodName Completed 引发事件。 在事件处理程序,可以检查 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("http://www.tailspintoys.com/image.jpg");
    }
    
    Private Sub loadButton_Click( _
      ByVal sender As System.Object, _
      ByVal e As System.EventArgs) _
      Handles loadButton.Click
    
      ' Replace with a real url.
      PictureBox1.LoadAsync("http://www.tailspintoys.com/image.jpg")
    
    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. 运行您的应用程序。

    映像下载开始后,你可以自由地移动窗体、 降到最低,和其最大化。

另请参阅

如何:在后台运行操作
基于事件的异步模式概述
不在生成中: Visual Basic 中的多线程处理

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文