Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Break out of loop on button press

Tags:

c#

foreach

I have a simple C# foreach loop, how can I break out of the loop when a button is pressed? It is not in a backgroundWorker thread so I can't use backgroundWorker.CancellationPending.


2 Answers

Create a boolean flag in the form. Attach an event handler to the buttons click event and set the flag to true in the event handler.

Check for the flag in the loop and if it's true, call "break". (A better option would be to use a while loop instead of a for loop with the check of the flag in the while condition)

Obviously the for loop will need to be on some form of background thread otherwise the GUI won't be responsive. If you don't know how to do this, check out either ThreadPool.QueueUserWorkItem or the BackgroundWorker. If you do use a BackgroundWorker you can use the inbuilt CancelAsync() method instead of coding your own cancel flag.

[Edit: As pointed out by others (below) and discussed in more depth here and here; you do need to either lock before accessing the bool or mark it as volatile]

[Don't forget to set the correct state of the flag before you start the loop.]

like image 193
Simon P Stevens Avatar answered Dec 31 '25 16:12

Simon P Stevens


Here is a not-so-good solution.

Call Application.DoEvents() in every iteration your loop. On Button-Click set a variable to True and in loop check that variable. If it is true, break otherwise continue.

As I said, this is not a very good solution. Application.DoEvents() can be very dangerous. The best option here to do is to have a background thread.

like image 23
Aamir Avatar answered Dec 31 '25 15:12

Aamir