不能在foreach循环中处理DataTable [英] Not able to dispose DataTable in foreach loop
问题描述
在我的Dispose方法中,我处理的数据集的一切如下:
In my Dispose method I am disposing everything a Dataset has as below:
foreach (DataTable myTable in this.Tables)
{
myTable.Dispose();
}
这里this.Tables是 public DataTableCollection Tables {get ; }
Here this.Tables is public DataTableCollection Tables { get; }
当这个电话接近这个电话时,我有56个表。
I am having around 56 tables in this.Tables when it comes near to this call.
它对几个表工作正常,但突然它引发:
It works fine for few tables but suddenly it throws:
System.InvalidOperationException:
集合修改错误
System.InvalidOperationException: Collection modified error
我不知道为什么会发生这种情况。
I am not sure why is this happening.
搜索这个异常很多,但我不能很好为什么它在我的应用程序中打破。
I tried to search for this exception a lot but i could not fine why it is breaking in my application.
可能是因为线程?或者我需要将它转换为列表?
May be because of threading? or I need to convert it to a list?
推荐答案
异常是因为当枚举时集合被修改。 这个回答解释得很好。
The exception is because the collection is modified when it's being enumerated. This answer explains well.
不同的是你枚举了一个 DataTableCollection
,它不是一个通用集合,所以链接答案中的解决方案在这种情况下是不合适的。您可以将集合转换为通用的,然后枚举它。
The difference is you are enumerating a DataTableCollection
, which is not a generic collection so the solution in the linked answer is not suitable in this case. You can cast the collection to a generic one and then enumerate it.
foreach (DataTable thisTable in this.Tables.Cast<DataTable>().ToArray())
这篇关于不能在foreach循环中处理DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!