How to stop long running loop using button

前端 未结 2 811
说谎
说谎 2021-01-17 08:50

I have c# application which having 2 buttons. First having for loop which is run 10k times. and each loop code execution take 1 second to finish.

    for(in         


        
2条回答
  •  天命终不由人
    2021-01-17 09:27

    The simplest solution (not best) is to add Application.DoEvents() into the loop to process button events:

    private bool cancel;
    
    public void loop()
    {
        for(int i=0;i<10000;i++){
          //My running code take 1 sec for each loop
           Application.DoEvents();
           if (cancel)
              break;
        }
    }
    
    public void cancelButton_Click(object sender, EventArgs e)
    {
          cancel=true;
    }
    

    Much better and still simple solution is to employ async Task (the rest of the code stays the same minus Application.DoEvents() call):

    private void loopButton_Click(object sender, EventArgs e)
    {
        new Task(loop).Start();
    }
    

    Beware that you should use this.Invoke(new Action(() => { } )); to access UI controls from the loop in this case.

提交回复
热议问题