Try, do you really mean a stop or do you mean a pause? If you mean a stop, then this is a piece of cake. Create a button click event handler for the button on which you want to be responsible for launching the background, and a button click event handler for the person responsible for stopping it. On the start button, make a call to the desktop method that fires the do_work event. Something like that:
private void startButton_Click(System.Object sender, System.EventArgs e) {
On your stop button, call a method that sets the background working CancellationPending to true, for example:
private void cancelAsyncButton_Click(System.Object sender, System.EventArgs e) {
Now remember to check the CancelationPending flag inside your desktop. Something like that:
private void KillZombies(BackgroundWorker worker, DoWorkEventArgs e) { while (true) { if (worker.CancellationPending) { e.Cancel = true; } } }
And your doWork method:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; KillZombies(worker, e); }
Hope this helps you in the right direction. Some additional readings:
http://msdn.microsoft.com/en-us/library/b2zk6580(v=VS.90).aspx
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
http://msdn.microsoft.com/en-us/library/waw3xexc.aspx
vitorbal
source share