您的位置:首页 > 其它

基于事件的异步模式——BackgroundWorker

2017-04-12 09:27 761 查看
转自strangeman原文 基于事件的异步模式——BackgroundWorker

  实现异步处理的方法很多,经常用的有基于委托的方式,今天记录的是基于事件的异步模式。利用BackgroundWorker组件可以很轻松的实现异步处理,并且该组件还支持事件的取消、进度报告等功能。本文以计算两个数X、Y的和为例。

  通过反编译可以看到,这个组件内部也是通过异步委托实现的,报告进度、取消事件等运用了事件技术实现,而事件的本质其实就是委托。

程序界面如下图,其中三个文本框分别为两个加数和处理结果,两个按钮为计算和取消,按钮下方为进度条。

/*
* 由SharpDevelop创建。
* 用户: David Huang
* 日期: 2015/9/8
* 时间: 14:54
*/
using System;
using System.Windows.Forms;

namespace BackgroundWorkerTest
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
this.backgroundWorker1.DoWork += this.BackgroundWorker1DoWork;
this.backgroundWorker1.ProgressChanged += this.BackgroundWorker1ProgressChanged;
this.backgroundWorker1.RunWorkerCompleted += this.BackgroundWorker1RunWorkerCompleted;
this.backgroundWorker1.WorkerReportsProgress = true;
this.backgroundWorker1.WorkerSupportsCancellation = true;
this.buttonCancel.Enabled = false;
}
void ButtonCalculateClick(object sender, EventArgs e)
{
this.buttonCalculate.Enabled = false;
this.textBoxResult.Text = string.Empty;
this.buttonCancel.Enabled = true;
this.backgroundWorker1.RunWorkerAsync(new Tuple<int,int>(Convert.ToInt32(this.textBoxX.Text), Convert.ToInt32(this.textBoxY.Text)));
}
void ButtonCancelClick(object sender, EventArgs e)
{
this.backgroundWorker1.CancelAsync();
}
void BackgroundWorker1DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 0; i < 10; i++) {
System.Threading.Thread.Sleep(500);
if (backgroundWorker1.CancellationPending) {
e.Cancel = true;
return;
} else {
backgroundWorker1.ReportProgress(i * 10);
}
}
var t = e.Argument as Tuple<int,int>;
e.Result = t.Item1 + t.Item2;
}
void BackgroundWorker1ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
void BackgroundWorker1RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
this.textBoxResult.Text = e.Cancelled ? "Canceled" : e.Result.ToString();
this.buttonCancel.Enabled = false;
this.buttonCalculate.Enabled = true;
this.progressBar1.Value = 100;
}
}
}


View Code

代码下载:点我
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: