问题
In my Dispose method I am disposing everything a Dataset has as below:
foreach (DataTable myTable in this.Tables)
{
myTable.Dispose();
}
Here this.Tables is public DataTableCollection Tables { get; }
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: 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?
回答1:
The exception is because the collection is modified when it's being enumerated. This answer explains well.
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())
来源:https://stackoverflow.com/questions/36215695/not-able-to-dispose-datatable-in-foreach-loop