This is the dowork code. I have even stepped through this. After e.cancel = true, DoWork runs once more ,it gets to the while loop, it sets e.Cancel to true again and then exits the function and never runs the Completed function.
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
//While the song is not over
while (!worker.CancellationPending )
{
if (progressBar1.Value == progressBar1.Maximum)
{
e.Cancel = true;
return;
}
else
{
//Keep ticking the progress bar one second
worker.ReportProgress(0);
Thread.Sleep(1000);
}
}
e.Cancel = true;
return;
}
Here is the code that cancels the worker. the WaitOne() will block untill it gets a signal from the RunWorkerCompleted.
if (this.backgroundWorker2.IsBusy)
{
this.backgroundWorker2.CancelAsync();
_resetEvent.WaitOne();
}
EDIT: Note that I have done this VV
backgroundWorker2.RunWorkerCompleted += backgroundWorker2_RunWorkerCompleted;
backgroundWorker2.WorkerSupportsCancellation = true;
did you set
?