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."
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…