using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp53
{
///
public partial class MainWindow : Window
{
BackgroundWorker bgWorker;
public MainWindow()
{
InitializeComponent();
cancelBtn.IsEnabled = false;
}
private void StartBtn\_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
startBtn.IsEnabled = false;
cancelBtn.IsEnabled = true;
bgWorker = new BackgroundWorker();
bgWorker.DoWork += BgWorker\_DoWork;
bgWorker.ProgressChanged += BgWorker\_ProgressChanged;
bgWorker.RunWorkerCompleted += BgWorker\_RunWorkerCompleted;
bgWorker.WorkerReportsProgress = true;
bgWorker.WorkerSupportsCancellation = true;
int maxItems = ;
progressBar1.Minimum = ;
progressBar1.Maximum = ;
statusTextBox.Text = "Starting...";
bgWorker.RunWorkerAsync(maxItems);
}
private void BgWorker\_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(e.Cancelled)
{
statusTextBox.Text = "Cancelled";
}
else
{
statusTextBox.Text = "Completed";
}
statusTextBox.IsEnabled = true;
cancelBtn.IsEnabled = false;
}
private void BgWorker\_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
double percent = (e.ProgressPercentage \* ) / ;
progressBar1.Value = Math.Round(percent, );
listBox1.Items.Add(new ListBoxItem { Content = e.ProgressPercentage + " item added" });
statusTextBox.Text = Math.Round(percent, ) + "% percent completed";
}
private void BgWorker\_DoWork(object sender, DoWorkEventArgs e)
{
int? maxItems = e.Argument as int?;
for(int i=;i<=maxItems.GetValueOrDefault();i++)
{
if(bgWorker.CancellationPending)
{
e.Cancel = true;
break;
}
Thread.Sleep();
bgWorker.ReportProgress(i);
}
}
private void CancelBtn\_Click(object sender, RoutedEventArgs e)
{
bgWorker.CancelAsync();
startBtn.IsEnabled = true;
}
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章