Skip to content

Instantly share code, notes, and snippets.

@ntotten
Created March 10, 2011 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ntotten/864811 to your computer and use it in GitHub Desktop.
Save ntotten/864811 to your computer and use it in GitHub Desktop.
public class CachedLocationService : LocationService
{
private static List<StoreLocation> locations;
private static DateTime expireTime = DateTime.UtcNow;
private static object syncLock = new object();
public CachedLocationService(DataModelContainer dataModelContainer)
: base(dataModelContainer) { }
public override StoreLocation GetByStoreNumber(int storeNumber)
{
return this.GetAll().Single(s => s.StoreNumber == storeNumber);
}
public override List<StoreLocation> GetAll()
{
if (locations == null)
{
UpdateCache();
if (locations == null)
{
throw new InvalidOperationException("There was an error loading the store locations from the database. The cache is currently null.");
}
}
else
{
var task = new Task(() => { UpdateCache(); });
task.Start();
}
return locations.ToList();
}
public override List<StoreLocation> GetByPosition(Position position, int numberToReturn = 10, double distanceLimit = 50)
{
return LocationService.GetByPosition(position, numberToReturn, distanceLimit, this.GetAll());
}
private void UpdateCache()
{
if (DateTime.UtcNow >= expireTime)
{
lock (syncLock)
{
if (DateTime.UtcNow >= expireTime)
{
List<StoreLocation> newLocations = null;
try
{
newLocations = base.GetAll();
}
catch
{
newLocations = null;
}
if (newLocations != null)
{
locations = newLocations;
expireTime = DateTime.UtcNow.AddHours(1);
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment