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;
}

上一篇:sql中判断是否存在某个对象


下一篇:掌握这些回答技术面试题的诀窍,让你offer拿到手软。