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
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.