110,567
社区成员
发帖
与我相关
我的任务
分享
private void FrmThawStateDisplay_Load(object sender, EventArgs e)
{
//显示数据库信息
this.timer1.Interval = 1000;
this.timer1.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.WorkerReportsProgress = true;//是否在异步操作里报告进度
backgroundWorker1.WorkerSupportsCancellation = true; //是否可以取消这个异步操作
}
#endregion
//开始backgroundworker异步处理
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync(20);//
}
int index = 0;
//backgroundworker异步要调用的方法
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
BackgroundWorker bw = (BackgroundWorker)sender;
int count = Convert.ToInt32(e.Argument);//count为20
for (int i = 0; i < count; i++)
{
if (bw.CancellationPending)//bw.CancellationPending最后一次调用BackgroundWorker的方法是RunWorkerAsync(falser)还是CancelAsync(true),
{
return;
}
index++;
Thread.Sleep(1000);
bw.ReportProgress(index, e.Cancel);
}
e.Result = "成功";
}
catch (Exception)
{
}
}
//backgroundworker异步处理返回的进度
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.label1.Text = e.ProgressPercentage.ToString();
}
//backgroundworker异步处理完成过后的事件
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// MessageBox.Show(e.Error.Message);
MessageBox.Show(e.Result.ToString());
}
//取消backgroundworker异步处理
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
常用属性