private static void UpdateTimestamp(ConcurrentLruRegexCacheNode result) { var timestamp = Stopwatch.GetTimestamp(); var resultTimestamp = result.Timestamp; // here we want to avoid updating this using Interlocked on a highly // used query, so we limit it to once per 10,000 ticks, which should // still be good enough if we need to start evicting if (timestamp - resultTimestamp > 10_000)//if our snapshot is over 10,000 ticks old { //If we fail this interlocked operation, it means that some other thread already updated the timestamp Interlocked.CompareExchange(ref result.Timestamp, timestamp, resultTimestamp); } }
private Regex GetUnlikely(string pattern) { var result = new ConcurrentLruRegexCacheNode( pattern, _neverCompile ? RegexOptions.None : RegexOptions.Compiled) { Timestamp = Stopwatch.GetTimestamp() }; var res = _regexCache.GetOrAdd(pattern, result); if (res != result) // someone else created it { return(res.RegexLazy.Value); } //We have reached the capacity and we will now clear 25% of the cache var currentCount = Interlocked.Increment(ref _count); if (currentCount >= _capacity) { ClearOldItems(); } return(res.RegexLazy.Value); }