Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Start And Stop A Continuously Running Background Worker Using A Button

Let's say I have a background worker like this:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
             while(true)
             {
                  //Kill zombies
             }
        }

How can I make this background worker start and stop using a button on a WinForm?

like image 244
sooprise Avatar asked Jun 17 '10 21:06

sooprise


People also ask

How do I pause my background worker?

if you want to pause and resume a BGW, split your task into smaller packets (or put the needed values (like a counter variable/state) into e. Result), stop the BGW at a safe point and in the RunWorkerCompleted event, dispose the worker, instanciate it again (or a second BGW) and fire it up when needed.

What is BackgroundWorker C#?

BackgroundWorker makes the implementation of threads in Windows Forms. Intensive tasks need to be done on another thread so the UI does not freeze. It is necessary to post messages and update the user interface when the task is done.

Is BackgroundWorker threaded?

BackgroundWorker, is a component in . NET Framework, that allows executing code as a separate thread and then report progress and completion back to the UI.

How do I restart my BackgroundWorker?

By creating a Task , the backgroundworker is can be stopped with the CancelAsync and restarted inside the Task. Not making a Task wil start the backgroundworker again before it is cancelled, as the OP describes.


1 Answers

Maybe you can use a manualresetevent like this, I didn't debug this but worth a shot. If it works you won't be having the thread spin its wheels while it's waiting

ManualResetEvent run = new ManualResetEvent(true);

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
{ 
     while(run.WaitOne()) 
     { 
         //Kill zombies 
     } 
} 

private void War() 
{ 
    run.Set();
} 

private void Peace() 
{ 
    run.Reset();
}
like image 78
Steve Sheldon Avatar answered Oct 13 '22 01:10

Steve Sheldon