Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

c# - Which ADO.NET DataSet/DataTable Methods Are Safe For Multiple Reader Threads?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...