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.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.]