Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

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’?
Posted
Updated 14-Feb-11 20:38pm
v10
Comments
JF2015 15-Feb-11 2:25am    
Edited to add code formatting.

I am having an example here. say in this example MyBusyObject class has the business logic.

Follow the example. Ask me if any doubt arises

In the business logic code (in class files)...

C#
public interface IObservable
{
    void notify();
}
public interface IObserver
{
    void executeMessage(bool isStop);
}

public class MyBusyObject:IObserver
{
    int dummyValue;
    public bool isStop;
    public void busyFunction()
    {
        for(int i=0;i<1000000;i++){
            System.Threading.Thread.Sleep(1000);
            if (isStop == true) {
                //just for testing purpose
                System.Windows.Forms.MessageBox.Show("Loop stoped at " + i.ToString());
                //use return null if the function returns or whatever you may need to do
                break;
            }
            dummyValue = i;
        }
     }
    public void executeMessage(bool isStop)
    {
        this.isStop = isStop;
    }
}



In the form code...
C#
public partial class Form1 : Form,IObservable
{

    private IList<IObserver> myObservers = new List<IObserver>();
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.WorkerSupportsCancellation = true;
        backgroundWorker1.RunWorkerAsync();
    }
    private void button2_Click(object sender, EventArgs e)
    {
        backgroundWorker1.CancelAsync();
        notify();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        MyBusyObject obj = new MyBusyObject();
        myObservers.Add(obj);
        for (int i = 0; i < 5; i++)
        {
            if ((backgroundWorker1.CancellationPending == true))
            {
                e.Cancel = true;
            }
            obj.busyFunction();
        }
    }

    public void notify()
    {
        foreach (IObserver observer in myObservers)
        {
            observer.executeMessage(true);
        }
    }


}

Button1 is for start and button2 for stop. I am calling the busyfunction from 5 objects and stopping it by pressing the button2

Once your busy function returned, background worker stops thread automatically
 
Share this answer
 
v2
Comments
Sandeep Mewara 15-Feb-11 3:23am    
Good answer! 5!
msanaei 12-Jul-15 5:14am    
Thanks Albin, but what if busyFunction() was not as simple as a for loop?
for example if the busyFunction() was as following
busyFunction()
{
method1()
method2()
foreach(var x in y)
{
method3()
}
....
}

Should I check (isStop == true), before each line of code or at least before every method call?
AlbinAbel's solution is correct, I would just change the busyFunction to make it return a bool: true if busyFunction finished normally, false if it was cancelled, so you can get the return value back from the thread function and assign the return value to e.Cancel:

In addition to this solution, I remind you that setting e.Cancel to true will not make your thread function stop. This property is usefull only if you handle the RunWorkerCompleted event. Here you may check whether your thread function finished completely, or was canceled, or was terminated due to an unhandled exception.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900