Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help to stop the BackgroundWorker thread

Tags:

c#

window

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’?

like image 744
Tina Avatar asked Feb 14 '11 11:02

Tina


1 Answers

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().

like image 151
Lloyd Avatar answered Oct 23 '22 08:10

Lloyd