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

后端 未结 5 2192
春和景丽
春和景丽 2020-12-01 22:10

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

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
             while(true)
          


        
5条回答
  •  星月不相逢
    2020-12-01 22:47

    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();
    }
    

提交回复
热议问题