Created
March 10, 2011 20:05
-
-
Save ntotten/864811 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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