您的位置:首页 > 编程语言 > C#

c#中关于backgroundWorker控件的用法

2010-12-30 10:29 387 查看
所需控件如下: 三个textbox,两个button,一个进度条,一个backgroundWorker控件

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
//设置计算按扭与取消按扭的使用属性以及进度条的进度值
this.button1.Enabled = false;
this.textBox3.Text = string.Empty;
this.button2.Enabled = true;
this.progressBar1.Value = 0;
backgroundWorker1.RunWorkerAsync(new CalcInput(int.Parse(this.textBox1.Text), int.Parse(this.textBox2.Text)));//开始执行后台操作
}

//当执行后台操作时,后台线程开始执行此操作
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
CalcInput input = (CalcInput)e.Argument;
//System.Threading.Thread.Sleep(5000);
//e.Result = input.x + input.y;
for (int i = 0; i < 10; i++)
{
System.Threading.Thread.Sleep(500);
backgroundWorker1.ReportProgress(i * 10);
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
}
e.Result = input.x + input.y;
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage; //设置进度条的value值
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//this.textBox3.Text = e.Result.ToString();
//this.button2.Enabled = true;
//this.button1.Enabled = false;
//this.progressBar1.Value = 100;
if (e.Cancelled)
{
this.textBox3.Text = "cancelled";

}
else
{
this.textBox3.Text = e.Result.ToString();
}
this.button2.Enabled = true;
this.button1.Enabled = false;
this.progressBar1.Value = 100;
}

private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();//执行此操作时,需将backgroundWorker1控件WorkerSupportCancellation属性设置为true
}
}

//记录两个文本框的值
public struct CalcInput
{
public CalcInput(int x, int Y)
{
this.x = x;
this.y = Y;
}
public int x;
public int y;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: