private void RefreshIfNecessary() { CachedInstance ci = current; if (ci == null || updateTimer.ElapsedMilliseconds - ci.createdAt >= maxAgeMs) { lock (myLock) { ci = current; if (ci == null || updateTimer.ElapsedMilliseconds - ci.createdAt >= maxAgeMs) { current = new CachedInstance(createNewObjectFunc(), updateTimer); } } } else if (updateTimer.ElapsedMilliseconds - ci.createdAt >= minAgeMs) { SetTimeout.OnBackground(() => { ci = current; if (updateTimer.ElapsedMilliseconds - ci.createdAt >= minAgeMs) { lock (myLock) { ci = current; if (updateTimer.ElapsedMilliseconds - ci.createdAt >= minAgeMs) { current = new CachedInstance(createNewObjectFunc(), updateTimer); } } } }, 0); } }
/// <summary> /// Reloads the cached object now without regard for the current age. Returns a reference to the object created by this method. /// </summary> public T Reload() { Interlocked.Increment(ref updateCounter); try { CachedInstance ci = current = new CachedInstance(createNewObjectFunc(), updateTimer); return(ci.instance); } finally { Interlocked.Decrement(ref updateCounter); } }
public object ActivateInstance(IObjectAssemblySpecification registration) { string key = registration.Key; CachedInstance ci = null; if (_cache.TryGetValue(key, out ci)) { lock (_syncLock) ci.LastCacheHit = DateTime.UtcNow; } else { ci = new CachedInstance { Instance = registration.CreateInstance(), LastCacheHit = DateTime.UtcNow }; _cache.TryAdd(key, ci); } MaybeGroomCache(); return(ci.Instance); }
public void FlushCache(IObjectAssemblySpecification registration) { CachedInstance _ = null; _cache.TryRemove(registration.Key, out _); }
private bool NeedsUpdate(long ageLimitMs) { CachedInstance ci = current; return(ci == null || updateTimer.ElapsedMilliseconds - ci.createdAt >= ageLimitMs); }
public static MockAuthentication Get() => CachedInstance.Copy();