问题
I am creating a custom cache object for data that is relatively static and is periodically updated from the DB. I have chosen to use a strongly-typed DataSet to store the cached data. Now, access for reading and refreshing (clients cannot write to the cache, only refresh it) to the custom cache object is synchronized via ReaderWriterLockSlim. HOWEVER, I want to ensure that clients of the cache cannot corrupt the data (DataTables, DataRows, etc.) within the strongly-typed data set by concurrently modifying its constituent objects, even though clients ~shouldn't~ change the data. So, my approach is, upon looking up a cache item, clone the strongly typed DataSet and populate it with copies of the required row and its related parent/children rows and return that to the client. Basically, return a copy of the immutable cache data to the client so even if they try to modify it, no other threads will be affected.
My question is, can this safely be done within the ReaderWriterLockSlim read lock? More directly, are methods like DataSet.Clone, DataTable.ImportRow, inherently safe for reader threads, i.e. are they read-only operations on the cloned/copied object? Consider this note from the MSDN documentation for DataSet, DataTable, etc.
"This type is safe for multithreaded read operations. You must synchronize any write operations."
回答1:
Yes. The DataSet and DataTable and related items are threadsafe when it comes down to reading. As is stated by your own quote.
So as long as each threat clones your cache-items and then modifies the clones, you have nothing to worry.
And yes, this can all be done safely withing the scope of a ReaderWriterLockSlim, which is made for synchronizing multiple read operations and one write operation.
回答2:
The following ADO.NET types are safe for multithreaded read operations:
- DataRowCollection
- DataTableCollection
- DataColumnCollection
- DataColumn
- DataViewSetting
- DataRelation
- DataRelationCollection
- DataRow
- DataViewManager
- DataRowView
- ForeignKeyConstraint
- ConstraintCollection
- Constraint
- DataTable
- DataSet
- DataViewSettingCollection
- DataView
They are not safe for multithreaded write operations though.
来源:https://stackoverflow.com/questions/16155180/which-ado-net-dataset-datatable-methods-are-safe-for-multiple-reader-threads