whats the correct way to cache a object(DataSet) and then get it and when it expires repopulate it with out a major hiccup in the application... the application relies on this data to be there for read only purposes.
A:
I assume your problem is the fact that repopulating it can take some time, and that you're not really worried about slightly stale data? In that case, you can probably do this:
class MyClass
{
private DataSet cached;
private Thread repopulateThread;
public DataSet GetDataSet() {
lock(this) {
if (/*cached has expired*/ && populateThread == null) {
populateThread = new Thread(PopulateCachedValue);
populateThread.Start();
}
return cached;
}
}
private void PopulateCachedValue() {
DataSet ds = /* fetch new DataSet */
lock(this) {
cached = ds;
}
populateThread = null;
}
}
Obviously, this is just pseudocode, but you should be able to see what's going on: when the cached value expires, we spin up a new thread to fetch the new value, but while that thread is still working, we continue to serve up the old cached value.
Finally, when the thread has finished it's work, we replace the old cached value with the new one.
Dean Harding
2010-03-09 05:40:46