这样么?
using System;
using System.Collections.Generic;
using
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace ThreadUpdateUI
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
backgroundWorker1.RunWorkerAsync(1000);
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bk=sender as BackgroundWorker;//把serder转化为BackgroundWorker(后台操作)
int count = (int)(e.Argument);//从 DoWorkEventArgs 参数的 Argument 属性中提取该操作所需的所有参数.并保存起来.
e.Result = longtime(count, bk, e);//将计算的结果赋给 DoWorkEventArgs 的 Result 属性。
}
Random rd = new Random();
long longtime(int pp,BackgroundWorker bk,DoWorkEventArgs e)
{
long time=0;
int i = 0;
while (i < pp)
{
i++;
//判断是否取消后台操作
if (bk.CancellationPending)
{
e.Cancel = true;
break;
}
else
{
time += i;
}
//完成率
int view = (int)((float)i / pp * 100);
bk.ReportProgress(view);//已完成后台操作的百分完成率,范围0%-100%
System.Threading.Thread.Sleep(5);//sleep()里面的数字越少就越快
}
return time;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("取消");
}
else
{
MessageBox.Show(e.Result.ToString());
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;//获取异步任务的进度百分比
label1.Text = e.ProgressPercentage.ToString();//显示出来
}
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
}
}