During the optimization and upgrade of a company's business system over the past two days, the code in the form close event was changed by system. enviromen. change exit (0) to application. exit (); but this problem occurs. When you click the close button in the upper-right corner of the system, an exception occurs, "the set has been modified, and enumeration operations may not be performed. As shown in: What is the cause? After asking du Niang, the exception "the set has been modified and enumeration operations may not be performed" is mostly caused by the misuse of the foreach statement, and foreach is read-only, the data cannot be changed when the data is retrieved (including modification, deletion, and addition ). To avoid this problem, we should use the for loop. I have never considered the difference between for and foreach when operating collection objects. I always feel that foreach is more convenient. So I wrote a foreach loop to verify this statement. I used foreach to traverse a list and then added it to the foreach body. On the surface, the logic and writing method are correct, however, an exception occurs during running. I carefully checked the relevant procedures and did not find any use of foreach. However, this problem still persists. However, in the reproduction process, we found a detail, that is, "Are you sure you want to leave the system? "The prompt box appears twice. After you click the" close "button, a prompt box is displayed. Click" OK "and a prompt is displayed again. After you click" OK "again, an exception occurs. After discovering the details, I suddenly realized that the exception may occur due to the two pop-up dialog boxes. Normally, it should be displayed once. The focus of the question is why two confirmation dialog boxes are triggered? It should be related to the application. Exit () code. Application. Exit () indicates on msdn that it stops all information loops running on all threads and closes all windows of the application. This means that when application. Exit (); is executed, the form close event is triggered again, that is, the formclosing event, which leads to an endless loop. After realizing the problem, I adjusted the Writing Method: Put application. Exit (); In the formclosed event. After the main form is closed, run the program to exit. Again, after compiling the system, click the close button to exit normally. So far, the problem has been solved perfectly.
click the close button. When the application exits, the system prompts the related idea of "The set has been modified and enumeration may not be executed".