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.
You can get list by passing the key in your memory cache and add item to that list. List is reference type so changes you do will be affected to original object.
List<T>
is not thread safe...Either you have to go about using lock mechanism or you can use ConcurrentBag<T>
if order of elements are not important..