Collection modified error, when iterating using foreach loop
本问题已经有最佳答案,请猛点这里访问。
我在我的应用程序中具有以下功能:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | // Method To Save Logs Buffer In Memory To DB public void SaveLogsToDB() { // Proceed If There Is Any Logs In Buffer if (LogsViewer.DBLogEntries.Count > 0) { // Init string massInertStr ="INSERT INTO IC_Logs ([Date], [Time], [Type], [Entry], [Synced], [CreatedOn]) VALUES"; // Build Mass Insert String List<DBLog> currentLogEntries = LogsViewer.DBLogEntries; foreach (DBLog myDBLog in currentLogEntries) { // Generate Insert Statement massInertStr += String.Format("('{0}', '{1}', '{2}', '{3}', 0, GETDATE()),", myDBLog.Date, myDBLog.Time, myDBLog.Type, myDBLog.Entry.Replace("'","''")); } massInertStr = massInertStr.Remove(massInertStr.Length - 1); // Expect Errors try { // Execute Mass Insert MyDb.ExecuteNonQuery(massInertStr); // Clear Logs Buffer LogsViewer.DBLogEntries.RemoveAll(item => currentLogEntries.Contains(item)); } catch { } } } |
当我的应用程序运行时,偶尔会出现以下异常:
Collection was modified; enumeration operation may not execute.
此行出错:
您最好这样做,以深入克隆您列出的:
1 |