I have a helper class in a web app, and among the things it does is to present common, unchanging data objects as static properties. I'm loading these object as below:
public static class MyWebHelper
{
#region - Constants & Fields
private const string LocationCacheKey = "MyWebHelper_Locations";
private static object LocationLoadLock = new object();
private static MemoryCache m_SiteCache;
#endregion
#region - Properties
/// <summary>
/// Gets the uneditable collection of locations.
/// </summary>
public static ReadOnlyCollection<Location> Locations
{
get
{
EnsureLocationsCache();
return (ReadOnlyCollection<Location>)SiteCache[LocationCacheKey];
}
}
/// <summary>
/// Gets the MemoryCache object specific for my site cache.
/// </summary>
public static MemoryCache SiteCache
{
get
{
if (m_SiteCache == null)
{
m_SiteCache = new MemoryCache("MyWeb_SiteCache");
}
return m_SiteCache;
}
}
#endregion
#region - Methods
private static void EnsureLocationsCache()
{
lock (LocationLoadLock)
{
if (SiteCache[LocationCacheKey] == null)
{
//
// Load all Locations from the database and perform default sorting on location code.
//
List<Location> lLocations = DataAccess.GetAllLocations();
lLocations.Sort(delegate(Location l1, Location l2) { return string.CompareOrdinal(l1.Code, l2.Code); });
SiteCache[LocationCacheKey] = new ReadOnlyCollection<Location>(lLocations);
}
}
}
#endregion
}
My question is, does the locking help anything? I'm trying to reduce calls to the database, but is the locking just introducing overhead? The cached data is used pretty commonly throughout the site, and will almost never change. Also, am I locking in the right place?