【发布时间】:2019-03-06 21:52:44
【问题描述】:
我有一个包含许多表的DataSet dsComponents,它们都只在内存中,我不将它们与任何数据库同步。有时我需要删除所有行以释放一些内存,但该功能似乎不起作用(基于this answer)
if(dsComponents.Tables.Contains("MemoryHistory"))
{
dsComponents.Tables["MemoryHistory"].Rows.Clear();
}
但如果我在这段代码之后立即中断,则表明表中仍然存在所有行。我也试过了:
if(dsComponents.Tables.Contains("MemoryHistory"))
{
lock(dsComponents.Tables["MemoryHistory"])
{
foreach (DataRow row in dsComponents.Tables["MemoryHistory"].Rows)
{
row.Delete();
}
}
dsComponents.Tables["MemoryHistory"].Rows.Clear();
}
这个失败并显示“集合已修改;枚举操作可能无法执行”,即使使用lock。那么,如何清除表中的行但保留表本身(如主键等)?
【问题讨论】:
-
dsComponents.Tables["MemoryHistory"].Rows.Clear()应该可以正常工作。您确定它正在命中那行代码并且没有其他任何干扰吗? -
是的,至少根据 VS 调试器它正在命中。我也在检查行被清除后立即休息
-
您不能使用
foreach循环然后在循环内向集合中添加/删除元素,因此您可以尝试老式的for循环,但要倒退,for (int i = dsComponents.Tables["MemoryHistory"].Rows.Count - 1; i >= 0; i--)和然后在循环内调用dsComponents.Tables["MemoryHistory"].Rows[i].Delete() -
@jtate 成功了,谢谢
标签: c#