Bug 18213

Summary: System.Runtime.Caching.MemoryCache doesn't honor SlidingExpiration
Product: [Mono] Class Libraries Reporter: Craig Minihan <craig>
Component: System.WebAssignee: Bugzilla <bugzilla>
Status: RESOLVED FIXED    
Severity: normal CC: lexas, masafa, mono-bugs+mono
Priority: ---    
Version: 3.2.x   
Target Milestone: Untriaged   
Hardware: PC   
OS: Linux   
Tags: Is this bug a regression?: ---
Last known good build:

Description Craig Minihan 2014-03-06 07:44:16 UTC
MemoryCache items which are set to SlidingExpiration should not expire if accessed before their timeout. Calling Get(KEY) should update their expiry value, however this value is not updated and the items expire based on NOW + TIMESPAN when they were fist added. This is a test case which you are drop into MemoryCacheTest.cs:

[Test]
public void TestCacheSliding ()
{	
	var config = new NameValueCollection ();
	config["cacheMemoryLimitMegabytes"] = 0.ToString ();
	config["physicalMemoryLimitPercentage"] = 100.ToString ();
	config["__MonoEmulateOneCPU"] = true.ToString ();

	// it appears that pollingInterval does nothing, so we set the Mono timer as well
	config["pollingInterval"] = new TimeSpan (0, 0, 2).ToString ();
	config["__MonoTimerPeriod"] = 2.ToString ();
	
	using (var mc = new MemoryCache ("TestCacheSliding",  config)) {	
		Assert.AreEqual (0, mc.GetCount (), "#CSL1");

		var cip = new CacheItemPolicy();
		cip.SlidingExpiration = new TimeSpan(0, 0, 2);				
		mc.Add("slidingtest", "42", cip);

		for (int i = 0; i < 40; i++) {
			global::System.Threading.Thread.Sleep(250);
			
			var item = mc.Get("slidingtest");
			Assert.AreNotEqual (null, item, "#CSL2-" + i);
		}			
	}
}

The item should not expire in the loop, according to MS: "A span of time within which a cache entry must be accessed before the cache entry is evicted from the cache" - I can't see any code in Get() where sliding expired items are updated, so they always expire based on the initial expiresAt value.
Comment 1 Craig Minihan 2014-03-07 07:55:24 UTC
I'll attempt a fix this this one shortly
Comment 2 Craig Minihan 2014-03-26 20:44:28 UTC
Fix made in pull #971
Comment 3 Alexis Christoforides 2014-04-28 17:27:44 UTC
Pull #971 was merged on master (+ trivial test timer adjustments), commit 2d9b230c73adb68013e8757ddb09ddd20fc359ef.