I want to code an auto clear cache which in real scenario clears all items in cache once in many hours but has constant read hits. Since clearing and reading are from different threads this data structure needs to be thread safe. Want to avoid locks if possible with this constant read but very seldom write. With _cache marked as volatile and CleartheCache() being only an assignment (atomic) is this threadsafe ?
public class AutoClearCache
{
volatile IDictionary<Key,Resource> _cache = new Dictionary<Key, Resource>();
public AutoClearCache(TimeSpan autocleanInterval)
{
var observable = Observable.Interval(autocleanInterval);
observable.Subscribe((r) => CleartheCache());
}
private void CleartheCache()
{
_cache = new Dictionary<Key, Resource>();
}