我用静态DataTable对象记录用户上线下线,一开始没有问题,大概半天以后出现一下错误,也不知道是什么问题,一旦出现这个问题,程序就挂掉了,即使用了try和catch也不行。错误如下: DataTable 内部索引已损坏:“5”。 异常详细信息: System.InvalidOperationException: DataTable 内部索引已损坏:“5”。 源错误: 执行当前 Web 请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪信息确定有关异常原因和发生位置的信息。 堆栈跟踪:
|
也在优快云上面发了帖子,但是一直没有解决,后来在MSDN上面寻到了解决方法,放上来让大家给大家参考。
解决的办法其实很简单,只要了解出错原因。 原文如下: A DataTable is thread safe for read operations but not for write operations. So this means you can store a DataTable in the cache and extract it and use it in a read only fashion and it will work fine. However, creating a DataView on a DataTable is a write operation on a DataTable. Most people don't know this, and its not very intuitive so I don't blame them for not knowing this. What happens when you create a DataView on a DataTable is the DataView will create an index on the DataTable and this index is stored in the DataTable. The reason for this is performance, for example if you create a DataView saying "F1=1" as the criteria, this creates an internal index on the DataTable to locate this information. Later on if you create another DataView with the same criteria, the index is reused, so this improves performance. However the fact that these indexes are stored inside the DataTable means that these are write operations to the DataTable and thus they are not thread safe. So if you are creating random DataViews on the DataTable you are constantly creating new indexes. If you are creating the same type of DataView over and over you are constantly reusing existing index. So unfortunately you need to serialize the creating of DataViews over the DataTable. You could do this for example to avoid the problem: lock(myDataTableFromCache) { dv = new DataView(myDataTableFromCache,...); } So lock using the DataTable as the locking object and lock when creating the DataView should solve the problem. 下面是原文地址:http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=277680&SiteID=1&PageID=1 |