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

后端 未结 5 2183
春和景丽
春和景丽 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:49

    I haven't tested this, I have code somewhere that I'll have to see exactly what I did, but something like this is an adaptation of Fredrik's answer:

    private bool _performKilling;
    private object _lockObject = new object();
    
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
         while(true)
         {
    
             if (_performKilling)
             {
                 //Kill zombies
             }
             else
             { //We pause until we are woken up so as not to consume cycles
                 Monitor.Wait(_lockObject);
             }
         }
    }
    
    private void StartKilling()
    {
        _performKilling = true;
        Monitor.Pulse(_lockObject);
    }
    
    private void StopAllThatKilling()
    {
        _performKilling = false;
    ]
    

    More complete example of this pattern here:

    https://github.com/AaronLS/CellularAutomataAsNeuralNetwork/blob/fe9e6b950e5e28d2c99350cb8ff3157720555e14/CellLifeGame1/Modeling.cs

提交回复
热议问题