wpf 异步加载 只需6段代码
private BackgroundWorker worker = null;
ProgressBar probar = new ProgressBar();
private int percentValue = 0;
private int percent;
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
worker = new BackgroundWorker();
worker.WorkerReportsProgress=true;
worker.WorkerSupportsCancellation = true;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompleteWork);
percentValue = 1000;
this.probar.Maximum = 100;
// 执行后台操作
worker.RunWorkerAsync();
}
/// <summary>
/// 完成时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CompleteWork(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("处理完毕!");
}
//进度更改时
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//probar.Value = double.Parse(e.ProgressPercentage.ToString());
percent = (int)(e.ProgressPercentage / percentValue);
this.text1.Text = "处理进度:" + Convert.ToString(percent) + "%";
probar.Value = percent;
}
/// <summary>
/// 执行
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = ProcessProgress(worker, e);
}
private int ProcessProgress(object sender, DoWorkEventArgs e)
{
for (int i = 0; i <= 1000000; i++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
return -1;
}
else
{
// 状态报告
worker.ReportProgress(i);
// 等待,用于UI刷新界面,很重要
System.Threading.Thread.Sleep(1);
}
}
return -1;
}