定时任务

使用backgroundWorker+Timer+Parallel+ProgressBar


System.Timers.Timer timer = new System.Timers.Timer();//计时器

private bool isCancel;//是否终止线程

private int Minutes;//任务间隔时间


#region 定时执行任务
private void timeTask()
{
   if (Minutes <= 0)
   {
    Minutes = 10;
   }
   timer.Interval = Minutes * 60000;
   timer.Enabled = true;
   timer.AutoReset = true;
   timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
}

private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    StartWorker();
}
#endregion

#region backgroundWorker
        /// <summary>
        /// 开始工作
        /// </summary>
        private void StartWorker()
        {
            if (this.backgroundWorker1.IsBusy)//启动时候判断是否还在运行
            {
                return;
            }
            isCancel = false;//是否终止停止任务this.backgroundWorker1.WorkerReportsProgress = true;
            this.backgroundWorker1.WorkerSupportsCancellation = true;
            this.backgroundWorker1.RunWorkerAsync();//启动任务
        }

        /// <summary>
        /// 暂停任务
        /// </summary>
        private void CancelStop()
        {
            if (this.backgroundWorker1.IsBusy)//启动时候判断是否还在运行
            {
                this.backgroundWorker1.CancelAsync();//提前终止任务
            }
else
{
StopHandel();
} }
//停止定时任务 private void StopHandel() { this.Invoke(new Action(() => timer.Stop())); } //刷新进度 private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { this.Invoke(new Action(() => this.pbcalculate.Value = e.ProgressPercentage));//刷新进度条 this.Invoke(new Action(() => this.labitems.Text = "提交进度:" + e.UserState.ToString()));//lable文本显示百分比 this.Invoke(new Action(() => this.labitems.Update())); } //工作线程 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { var ReportAction = new Action<int, int>((counts, index) => { decimal indexs = (decimal)index; decimal count = (decimal)counts; decimal items = (indexs * 10000) / count; var i = (items / 100).ToString("0.00"); int it = Convert.ToInt32(items); this.backgroundWorker1.ReportProgress(it, String.Format("{0}%", i)); if (this.backgroundWorker1.CancellationPending)//是否结束线程 { e.Cancel = true; isCancel = true; StopHandel(); } }); HandelDatas(ReportAction); } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Cancelled)//是否提前结束任务 { SetInfo("任务终止..."); } else { SetInfo("休眠中..."); } } #endregion private void UpdataPaths(List<string> data, Action<int, int> ReportProcess) { int counts = data.Count;//数据量 int Process = 0; Exception exception = null; object objLock = new object(); Parallel.For(0, counts, new ParallelOptions() { MaxDegreeOfParallelism = 5 }, (i, loopState) => { if (exception != null) return; lock (objLock) { string error = ""; try { if (isCancel) loopState.Break(); //处理任务 Process++; if (ReportProcess != null) ReportProcess(data.Count, Process); } catch (Exception ex) { error = ex.Message; exception = ex; } } }); if (exception != null) throw exception; }

cs界面处理显示数据

posted @ 2018-11-23 14:47  世人皆萌  阅读(212)  评论(1编辑  收藏  举报