DialogResult result = MessageBox.Show($"当前失败数据共计{failCount}条,是否上传?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { // 后台线程查询数据 toolStripProgressBar1.Value = 0; this.backgroundWorker1.RunWorkerAsync(dataTable); //可以禁用其他控件防止出现后台处理数据,出现异常 }
backgroundWorker事件:
#region [backgroundWorker1事件] private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { if (e.Argument is DataTable scoreUploadTable) { ScoreUpload scoreUpload = new ScoreUpload(); int index = 1; int count = scoreUploadTable.Rows.Count; //获得表数据数量 foreach (DataRow rowsTable in scoreUploadTable.Rows) { scoreUpload = GetRowsInfo(rowsTable); //获得对象数据 examinterface.QryXml(GetQuerySQL(SqlStatusEnum.UPLOAD, scoreUpload)); //上传到数据库 backgroundWorker1.ReportProgress(index * 100 / count); if (backgroundWorker1.CancellationPending) { e.Cancel = true; return; } index++; } } } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { this.toolStripProgressBar1.Value = e.ProgressPercentage; } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { this.toolStripProgressBar1.Value = 100; MessageBox.Show("成绩失败数据上传完成"); RefreshBindTable(SqlStatusEnum.FUZZY_QUERY); } #endregion
取消按钮backgroundWorker1事件:
private void toolStripButton_Cancel_Click(object sender, EventArgs e) { if (backgroundWorker1.IsBusy) { backgroundWorker1.CancelAsync(); } }
private ScoreUpload GetRowsInfo(DataRow rows) { ScoreUpload scoreUpload = new ScoreUpload { Lsh = rows["S_LSH"].ToString(), // 学员编号 StudentName = rows["S_XM"].ToString(), // 学员姓名 IdCardNumber = rows["S_ZJHM"].ToString(), // 证件号码 Numbers = rows["S_DJC"].ToString(), // 考试次数 ExamDate = rows["S_KSRQ"].ToString(), // 考试日期 ExamDateTime = Convert.ToDateTime(rows["D_KSSJ"]), // 考试时间 ExamType = rows["S_KSLX"].ToString() // 考试类型 }; return scoreUpload; }