I have the following function in my application:
// 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 { }
}
}
When my application runs, every now and then I get the following exception:
Collection was modified; enumeration operation may not execute.
The error occurs on this line: foreach (DBLog myDBLog in currentLogEntries) { ... }
Isn't currentLogEntries
a copy of the collection rather than a reference? I am not sure why this error is occurring or how to prevent it.