namespace WindowsApplication1
{
///
/// Interaction logic for Window1.xaml
///
public partial class Window1 : System.Windows.Window
{
private BackgroundWorker _worker;
public Window1()
{
InitializeComponent();
}
private void StartWorker(object sender, RoutedEventArgs e)
{
_worker = new BackgroundWorker();
_worker.WorkerReportsProgress = true;
_worker.WorkerSupportsCancellation = true;
_worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
BackgroundWorker worker = s as BackgroundWorker;
for (int i = 0; i < 10; i++)
{
if (worker.CancellationPending)
{
args.Cancel = true;
return;
}
Thread.Sleep(1000);
worker.ReportProgress(i + 1);
}
};
_worker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args)
{
_progressBar.Value = args.ProgressPercentage;
};
_worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
_btnStart.IsEnabled = true;
_btnCancel.IsEnabled = false;
_progressBar.Value = 0;
};
_worker.RunWorkerAsync();
_btnStart.IsEnabled = false;
_btnCancel.IsEnabled = true;
}
private void CancelWorker(object sender, RoutedEventArgs e)
{
_worker.CancelAsync();
}
}
}
No comments:
Post a Comment