I am trying to cancel a background worker in WinForms with CancelAsync() but this isn't setting the IsBusy property of the worker to false.
The function that closes the worker is meant to restart the worker after doing some work. To do this, I use the IsBusy property to check if the worker has closed before starting it again.
private void buttonStart_Click(object sender, EventArgs e)
{
backgroundWorker1.WorkerSupportsCancellation = true;
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
buttonStart.Enabled = false;
}
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
BackgroundWorker worker = (BackgroundWorker)sender;
while (!worker.CancellationPending)
{
// Does some work
}
}
private void buttonRestart_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation && backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
buttonStart.Enabled = true;
}
// Do some work
// ...
if (!backgroundWorker1.IsBusy) // Worker is busy here
{
backgroundWorker1.RunWorkerAsync();
}
}
Update
After much troubleshooting and debugging, I could not find a direct solution to the problem above.
I did however find that BGW is quite outdated (first released with .Net 2.0), it has become somewhat obsolete and has been mostly replaced by Task/await. I was able to port my code over from the background worker to an async task and it now works and behaves as expected.
BackgroundWorkerhas aCancellationPendingproperty that, as its name suggests, returnstrueif cancellation has been signalled by calling theCancelAsyncmethod. You can use this property in combination withIsBusyto achieve what you want.