using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Caching; using Xunit; namespace Demo.Caching.Test { class MemoryCacheManagerTest { [Fact] public void Test() { CacheItemPolicy policy = new CacheItemPolicy(); policy.SlidingExpiration = TimeSpan.FromSeconds(1); MemoryCache.Default.Set("cacheKey4",4,policy); Assert.Equal(4,MemoryCache.Default.Get("cacheKey4")); System.Threading.Thread.Sleep(600); Assert.Equal(4,MemoryCache.Default.Get("cacheKey4")); // Here I get error // Expected: 4,Actual: (null) System.Threading.Thread.Sleep(1000); Assert.Null(MemoryCache.Default.Get("cacheKey4")); } } }
解决方法
可能原因是睡眠是非确定性的.它不会暂停你的线程600毫秒.它暂停线程至少600毫秒.如果你没有意识到,它可能会超过你设定的1秒滑动期限.