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)...
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) {
System.Windows.Forms.MessageBox.Show("Loop stoped at " + i.ToString());
break;
}
dummyValue = i;
}
}
public void executeMessage(bool isStop)
{
this.isStop = isStop;
}
}
In the form code...
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