1

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."

Mike S
  • 13
  • 4

2 Answers2

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.

Martin Mulder
  • 12,642
  • 3
  • 25
  • 54
  • Thanks for your reply Martin, that was my assumption. The point of clarification I was seeking was *which* methods are considered read-only, and if DataSet::Clone and DataTable::ImportRow were among them. On the surface it would appear so, but I wasn't sure if internal state is modified for clone, Copy, etc. – Mike S Apr 22 '13 at 22:18
  • You're welcome. I understand your doubt... but if MSDN says something about a class about read or write operations and thread safety, they mean read of write operations done by the developer, not what happens internally, since a developer cannot know what happens internally. Perhapse the state is modified after an read operation, but then it is the resposibility of that class itself to synchronize that. – Martin Mulder Apr 22 '13 at 22:46
0

The following ADO.NET types are safe for multithreaded read operations:

They are not safe for multithreaded write operations though.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104