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.
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.]
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.
You can use DoEvents, as Aamir suggested, as a quick fix.
For a more scalable and maintainable solution, you need to move the work to a separate thread. Then it's rather trivial to have a button click event set a flag to stop the loop. On the other hand, there is a bit more work to communicate the result back to the UI thread.