以上传文件为例;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.backgroundWorker1.ProgressChanged += BGWorker_ProgressChanged;
this.backgroundWorker1.DoWork += BGWorker_DoWork;
this.backgroundWorker1.RunWorkerCompleted += BGWorker_RunWorkerCompleted;
}
/// <summary>
/// 开始执行异步上传
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void btnGo_Click(object sender, EventArgs e)
{
this.btnCancel.Enabled = true;
this.progressBar1.Maximum = 100;
if (!this.backgroundWorker1.IsBusy)
this.backgroundWorker1.RunWorkerAsync(100);
}
private void BGWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//当前进度值
this.progressBar1.Value = e.ProgressPercentage;
string msg = e.UserState.ToString();
this.label1.Text = msg;
}
/// <summary>
/// 异步执行的功能
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void BGWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker backgroundWorker = sender as BackgroundWorker;
int sum = 0;
int endNumber = 0;
if (e.Argument != null)
{
endNumber = (int)e.Argument;
}
for (int i = 0; i < endNumber; i++)
{
sum += i;
string msg = “当前进度完成:” + i.ToString() + “%”;
backgroundWorker.ReportProgress(i, msg);
System.Threading.Thread.Sleep(100);
if (backgroundWorker.CancellationPending)
{
e.Cancel = true;
return;
}
}
e.Result = sum;
MessageBox.Show(“Completed!”);
}
/// <summary>
/// 取消当前进程
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void btnCancel_Click(object sender, EventArgs e)
{
this.backgroundWorker1.CancelAsync();
MessageBox.Show(“Canceled!”);
}
/// <summary>
/// 执行完成后的操作
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
private void BGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
this.Dispose();
this.Close();
}
this.btnCancel.Enabled = false;
if (e.Error != null)
{
Type errorType = e.Error.GetType();
switch (errorType.Name)
{
case “ArgumentNullException”:
case “MyException”:
MessageBox.Show(e.Error.Message);
break;
default:
//do something.
MessageBox.Show(e.Error.Message);
break;
}
}
}
}