You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
3.0 KiB

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using KPlan.Util;
namespace KPlan.Forms {
class KBackgroundWorker {
public BackgroundWorker backgroundWorker { get; set; }
private Window parent;
private KBgWorker2 pbDialog;
public KBackgroundWorker(Window parent) {
this.parent = parent;
//可以返回工作进度
backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
//允许取消
backgroundWorker.WorkerSupportsCancellation = true;
backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
//更新进度条
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
//backgroundWorker.DoWork += Query_Async;
//backgroundWorker.DoWork += backgroundWorker_DoWork;
//开始执行DoWork
//backgroundWorker.RunWorkerAsync();
}
public void Start(object param,bool disableCancel) {
if (backgroundWorker.IsBusy) {
return;
}
if (parent != null) {
parent.IsEnabled = false;
}
pbDialog = new KBgWorker2(parent, backgroundWorker);
if (disableCancel) {
pbDialog.tb_cancel.Width = 0;
pbDialog.tb_cancel.Visibility = Visibility.Hidden;
}
backgroundWorker.RunWorkerAsync(param);
}
public void Start(object param) {
if (backgroundWorker.IsBusy) {
return;
}
if (parent != null) {
parent.IsEnabled = false;
}
pbDialog = new KBgWorker2(parent, backgroundWorker);
backgroundWorker.RunWorkerAsync(param);
}
public bool IsCancel() {
return backgroundWorker.CancellationPending;
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
pbDialog.Dispatcher.Invoke(new Action(delegate {
pbDialog.Close();
}));
if (parent != null) {
parent.IsEnabled = true;
}
if (e.Error != null) {
KUtil.LogErr(e.Error);
MessageBox.Show(parent, "发生异常:" + e.Error.Message);
}
else {
if (e.Cancelled) {
MessageBox.Show(parent, "已取消");
}
//else {
// MessageBox.Show(parent, "操作完成");
//}
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) {
pbDialog.progressBar.Value = e.ProgressPercentage;
}
public void Progress(string text, int progress) {
pbDialog.Dispatcher.Invoke(new Action(delegate {
pbDialog.lable.Content = text;
}));
backgroundWorker.ReportProgress(progress);
}
}
}