我的应用程序中有以下功能:
// 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 { }
}
}
当我的应用程序运行时,我偶尔会遇到以下异常:
收藏被修改;枚举操作可能无法执行。
此行发生错误:foreach (DBLog myDBLog in currentLogEntries) { ... }
不是currentLogEntries
集合的副本而不是参考?我不确定为什么会出现这种错误或如何防止它。
答案 0 :(得分:3)
您最好这样做以深度克隆您的列表:
List<DBLog> currentLogEntries = new List<DBLog>(LogsViewer.DBLogEntries);