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?

Related posts

Recent Viewed