Im using some cache control in my c# web-api server.
Im using the following code:
private static MemoryCache _cache = new MemoryCache("ExampleCache");
public static object GetItems(string key) {
return AddOrGetExisting(key, () => InitItem(key));
}
private static List<T> AddOrGetExisting<T>(string key, Func<List<T>> valueFactory)
{
var newValue = new Lazy<List<T>>(valueFactory);
var oldValue = _cache.AddOrGetExisting(key, newValue, new CacheItemPolicy()) as Lazy<List<T>>;
try
{
return (oldValue ?? newValue).Value;
}
catch
{
_cache.Remove(key);
throw;
}
}
private static List<string> InitItem(string key) {
// im actually fetching a list from the db..but for the sake of the example
return new List<string>()
}
now, everything works nicely. BUT, this time I want to update something in my db and after that, I want to update the cache control so I wont have to query my db.
Assume im using an object which looks like this
Public class Foo{
public string Id;
public List<string> values;
}
And assume T is Foo in this example
I need to add an item to the list which is stored in the _cache by Foo's Id field. I would insanely appericate if the process will be thread safe.
TIA.
Foobe responsible for looking up and proxying to the cache or the database as required? (One possible way to solve the issue, at least) Alternately, you could useConcurrentBaginstead of list (I suggest you change the return type toIList<T>