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
It's not good practice to run long running operations in UI Thread
(thread where all UI events are handled - such as button click). You should run your loop in another that.
You can use Task Parallel Library (TPL)
:
private bool stopIt = false;
private void Form1_Load(object sender, EventArgs e)
{
Task task = Task.Factory.StartNew(() =>
{
for (int i = 0; i < 1000000000; i++)
{
if (!stopIt)
{
Console.WriteLine("Here is " + i);
}
else
{
break;
}
}
});
}
private void button1_Click(object sender, EventArgs e)
{
stopIt = true;
}
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(() => { <your code> } ));
to access UI controls from the loop in this case.