using System.Threading;
BackgroundWorker bw = new BackgroundWorker();
private void btnStartWorker_Click(object sender, EventArgs e)
{
if (!bw.IsBusy)
{
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(worker_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
bw.RunWorkerAsync();
btnStartWorker.Text = "Abbruch";
this.Cursor = Cursors.Wait;
}
else
{
bw.CancelAsync();
}
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 10000; i++)
{
if (bw.CancellationPending)
{
e.Cancel = true;
return;
}
// irgendwas rechnen
int iPc = (int)(((double)i / 10000.0) * 100);
// Fortschrittswert melden
bw.ReportProgress(iPc);
// BackgroundWorker schlafen schicken
Thread.Sleep(100);
}
}
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.BeginInvoke((MethodInvoker)delegate
{
pbProgressBar.Value = e.ProgressPercentage;
});
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// hier Dinge erledigen, die auftreten, wenn Backgroundworker fertig ist
this.Cursor = Cursors.Arrow;
if (e.Cancelled)
{
btnStartWorker.Text = "Start";
}
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
}