
正文
进度条--ProgressBar和BackgroundWorker
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
1) 需求:就餐打卡数据处理后,插入数据库中,用进度条显示过程
2) 思路:总进度为txt文本文件的行数(数据都是按照行写入),文本文件的大小
//BackgroundWorker对象有三个主要的事件:
//DoWork - 当BackgroundWorker对象的多线程操作被执行时触发。
//RunWokerCompleted - 当BackgroundWoker对象的多线程操作完成时触发。
//ProgressChanged - 当BackgroundWorker对象的多线程操作状态改变时触发。
//WorkerReportsProgress - 如果想让BackgroundWorker对象以异步的方式报告线程实时进度,必须将该属性的值设为true。
//WorkerSupportsCancellation 布尔类型,该值指示BackgroundWorker是否支持异步取消。
//BackgroundWorker对象的ReportProgress方法用于向主线程返回后台线程执行的实时进度。
//总后台线程
private BackgroundWorker bgwInsertData = new BackgroundWorker();
//求百分比
long totalCount = ;
decimal percent = ; //源--就餐打卡记录储存 目录
private string sourcefileDirectory = Application.StartupPath + "\\CardData";
private string destFileDirectory = Application.StartupPath + "\\CardDataBak"; public FrmReadText()
{
InitializeComponent(); bgwInsertData.WorkerReportsProgress = true;
bgwInsertData.WorkerSupportsCancellation = true; bgwInsertData.DoWork += new DoWorkEventHandler(bkWorker_DoWork);
bgwInsertData.ProgressChanged += new ProgressChangedEventHandler(bkWorker_ProgressChanged);
bgwInsertData.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bkWorker_RunWorkerCompleted);
} private void btnReadText_Click(object sender, EventArgs e)
{
//1.调用bgwInsertData的RunWorkerAsync方法,用来引发DoWork事件
bgwInsertData.RunWorkerAsync();
} void bkWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else if (e.Cancelled)
{
MessageBox.Show("取消操作!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else
{
MessageBox.Show("操作成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
//关闭该窗体
this.Close();
}
} void bkWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
lblResult.Text = "已获取数据" + e.ProgressPercentage.ToString() + "%";
} void bkWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
//2.在DoWork中调用自定义函数,并将引发DoWork事件的sender传递出去
insertData(worker);
}
3) 效果图:







