如何:使用支持基于事件的异步模式的组件
更新:2007 年 11 月
很多组件都提供了异步执行工作的选项。例如,使用 SoundPlayer 和 PictureBox 组件,您可以“在后台”加载声音和图像,主线程则继续运行而不会中断。
使用支持基于事件的异步模式概述的类上的异步方法就像将事件处理程序附加到组件的 方法名称Completed 事件一样简单,这与处理任何其他事件完全一样。当您调用 方法名称Async 方法时,您的应用程序将继续运行而不会中断,直到引发 方法名称Completed 事件才会停止。在您的事件处理程序中,您可以检查 AsyncCompletedEventArgs 参数来确定异步操作是已经成功完成,还是被取消了。
有关使用事件处理程序的更多信息,请参见 事件处理程序概述(Windows 窗体)。
下面的过程演示如何使用 PictureBox 控件的异步图像加载功能。
使 PictureBox 控件异步加载图像
在窗体中创建 PictureBox 组件的一个实例。
给 LoadCompleted 事件分配一个事件处理程序。
在此处检查异步下载过程中是否发生了任何错误,此处还可以检查是否取消了操作。
Friend WithEvents PictureBox1 As System.Windows.Forms.PictureBox
public Form1() { InitializeComponent(); this.pictureBox1.LoadCompleted += new System.ComponentModel.AsyncCompletedEventHandler(this.pictureBox1_LoadCompleted); }
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
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"); } }
向窗体添加两个按钮,名称分别是 loadButton 和 cancelLoadButton。添加 Click 事件处理程序,用于开始和取消下载。
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 loadButton_Click(object sender, EventArgs e) { // Replace with a real url. pictureBox1.LoadAsync("http://www.tailspintoys.com/image.jpg"); }
Private Sub cancelLoadButton_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles cancelLoadButton.Click PictureBox1.CancelAsync() End Sub
private void cancelLoadButton_Click(object sender, EventArgs e) { pictureBox1.CancelAsync(); }
运行应用程序。
在图像下载过程中,您可以自由移动窗体、最小化窗体和最大化窗体。