Need help to stop the BackgroundWorker thread. I am trying to stop a background worker thread. This is what I am doing:
On stop button click (UI layer):
if (backgroundWorker.IsBusy == true &&
backgroundWorker.WorkerSupportsCancellation == true)
{
backgroundWorker.CancelAsync();
}
On DoWork event (UI layer):
if ((backgroundWorker.CancellationPending == true))
{
e.Cancel = true;
}
else
{
//Function which progresses the progress bar is called
//here with its definition in business layer
}
Once the DoWork event is fired and my program control is in the function defined in Business layer, how do I revert back to the DoWork event to set ‘e.Cancel = true’?
Setting e.Cancel does nothing, if CancellationPending is true you need to basically break out of DoWork() using return or whatever (after you've stopped what you're doing).
Something like:
private void DoWork(...)
{
// An infinite loop of work!
while (true)
{
// If set to cancel, break the loop
if (worker.CancellationPending)
break;
// Sleep for a bit (do work)
Thread.Sleep(100);
}
}
DoWork() executes in a seperate thread to the UI thread, you can report back to the UI thread using BackgroundWorkr.ReportProgress().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With