Not able to dispose DataTable in foreach loop [closed]

青春壹個敷衍的年華 提交于 2019-12-20 07:47:49

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!