Last active
May 20, 2017 23:19
-
-
Save Drawaes/2d5d5979d2d38907c91b96892f8f132c to your computer and use it in GitHub Desktop.
Simple resetting cache
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
using System.Collections.Generic; | |
public class ReloadingCache | |
{ | |
private List<string> _cachedItems; | |
private System.Threading.Timer _timer; | |
public ReloadingCache() | |
{ | |
//Load the first lot of data to stop consumers getting null | |
_cachedItems = MyMethodThatGivesMeTheList(); | |
//Create a timer that will be called after 30k ms (30seconds) | |
//It will not fire again after that until you call change | |
_timer = new System.Threading.Timer(state => | |
{ | |
//Load our new list | |
var newList = MyMethodThatGivesMeTheList(); | |
//Swap the new list for the old list, ensuring that the swap is atomic | |
//you really don't want 1/2 a pointer | |
System.Threading.Interlocked.Exchange(ref _cachedItems, newList); | |
//Set the timer to fire 1 more time in another 30 seconds | |
_timer.Change(30000, System.Threading.Timeout.Infinite); | |
}, null, 30000, System.Threading.Timeout.Infinite); | |
} | |
public List<string> GetListToDoWork() | |
{ | |
//Ensure we have the lastest pointer to our list and not a cached one | |
//so we use the volatile read method (otherwise we might read the old | |
//one for a while | |
return System.Threading.Volatile.Read(ref _cachedItems); | |
} | |
private List<string> MyMethodThatGivesMeTheList() | |
{ | |
return new List<string>() | |
{ | |
"Test1", | |
"Test2" | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment