views:

37

answers:

3

I have a WinForms app (c#) that has a background thread that periodically grabs data from a data source, does some manipulation of it, and puts it in a DataTable. There are 1 or more components in the app that periodically poll this common data to do stuff with it. I'm wondering, what's the "right" way to synchronize this, so e.g. the components don't query the data while it's being updated?

Locking on something while the data is being updated won't work because the updating could take several seconds. So I thought, why not "double-buffer" it, e.g. update the data in a second DataTable, then when finished swap (locking just for the swap operation). Is this appropriate, or is there a better way to do this?

+1  A: 

This could work. Instead of locking, you may get away with marking the field reference as volatile.

This approach is actually recommended if consistency of data is important, but not necessarily their timeliness. In other words, if you application doesn't necessarily always need the latest and freshest data; as you will be getting some stale data while DataTable is being updated on the side.

Also, you need to be careful about aliasing (other references to DataStore) and ensure than you don't hold any other reference to it. Otherwise, you may have two inconsistent DataStores in your application.

notnoop
A: 

Double buffering is the way to go. It removes the issues of long reload times. Just be sure to have a nice locking mechanism for when you are replacing the existing data with the new one. :)

Is the data read only for the compnents? If they are changing the data you need to be careful about writting back and reading at the same time.

Craig
+1  A: 

In theory this sounds like a great solution. But there are a couple of gotchas that you need to look out for.

  • This is only a good solution if it's OK for the multiple WinForms components can have differing versions of the DataTable. In between component1 and component2 grabbing the new table a swap could occur causing them to get different versions. This can be fixed with additional locking techniques
  • When you say swap do you mean that the background thread publishes, so to speak, a new DataTable and starts populating a completely different one? Your post could be interpretted as there being only 2 total DataTable instances and the background thread is switching between them. If so that will cause synchronization problems. I don't think that's what you mean but wanted to check.
JaredPar