views:

354

answers:

3

What's the best pattern for making datasets threadsafe on write?

The best I can find by googling is 'implement a wrapper layer with locks' but at first blush this seems rather messy.

Can someone recommend / point me in the direction of a good solution to this? It seems likely to be a problem that has already been solved somewhere.

edit: I also need to bind the dataset to a ui grid, which complicates matters somewhat.

+1  A: 

It really depends, hugely, on the data in question.

If you're dealing with integer or reference type values, the Interlocked class can be superior to taking locks. Otherwise, successful synchronization typically means creating locking internal in the class.

The other alternative, however, is to make your main datasets work on immutable types. You can then just work on copies in individual threads, and only provide synchronization at the point of replacing values within the main set of data. This avoids locks in the individual copies-per-thread.

Reed Copsey
+1  A: 

"Implement a wrapper layer with locks" is the way to go.

The wrapper layer will likely use locking that is specific to the way your application uses the DataSets.

Attempting to design a generic solution for a class as complex as a DataSet is probably doomed to failure.

For example, enumerating properties will generally not be thread-safe - so you would need to hold a lock for as long as any caller is enumerating any of the many collection properties (DataSet.Tables, DataTable.Rows, ...).

Joe
+1  A: 

Implement a wrapper layer with locks. Seriously. You can't subclass the important methods, so as long as they are available, your thread safety can be broken.

Well, you can also implement a set of thread-safe extension methods and stick to those, but that will only work if you don't have to pass the DataSet to a 3rd party library which will access it directly.

Vilx-