Caching dataset passing value or reference?

125 views Asked by At

I'm going to cache an object. Obvious and popular check before read policy from http://msdn.microsoft.com/en-us/library/ms227644(v=vs.80).aspx

if (Cache["customerDataSet"] == null)
{
    dataSet = DataSetConfiguration.CustomerDataSet;
    Cache["customerDataSet"] = dataSet;
}
else
{
    dataSet = (DataSet)Cache["customerDataSet"];
}

secures existence of dataSet object. As dataSet is only a reference to an object, actual dataSet in cache can be gone in milliseconds, for example, in the middle of foreach loop. If so, this:

dataSet = ((DataSet)Cache["customerDataSet"]).Copy();

should be safer. Although cache can still expire during .Copy(). Am I right or this is just overthinking?

1

There are 1 answers

0
Jarosław Maruszewski On

Simple test:

DataSet d = (DataSet)Cache["myKey"];
int i = 0;
do
{
  i++;
} while (Cache["myKey"] != null);

Label1.Text = (Cache["myKey"] == null ? "gone with wind  " : null) + d.Tables[0].Rows.Count.ToString() + " took: " + i.ToString();

the do-while ends when cache is gone and dataset d is still accessible. You were right - overthinking.