本文整理汇总了C#中System.Runtime.Caching.MemoryCache.Add方法的典型用法代码示例。如果您正苦于以下问题:C# MemoryCache.Add方法的具体用法?C# MemoryCache.Add怎么用?C# MemoryCache.Add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Runtime.Caching.MemoryCache
的用法示例。
在下文中一共展示了MemoryCache.Add方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ClearAllCachesTest
public void ClearAllCachesTest()
{
const string prefix = "123123af";
var fk1 = FullKey(prefix, "111");
var fk2 = FullKey(prefix, "222");
var memoryCache = new MemoryCache("sdgkmnsdlkghn");
_objectCacheFactory.Setup(x => x.Create()).Returns(memoryCache).Verifiable();
Assert.AreEqual(0, memoryCache.GetCount());
memoryCache.Add(fk1, new MemoryCacherTests.One(), new CacheItemPolicy());
memoryCache.Add(fk2, new MemoryCacherTests.One(), new CacheItemPolicy());
Assert.AreEqual(2, memoryCache.Count());
new CacheCleaner(_objectCacheFactory.Object).Clean();
Assert.AreEqual(0, memoryCache.GetCount());
}
示例2: ShouldExpireCacheAfterConfigurableTime
public void ShouldExpireCacheAfterConfigurableTime()
{
const string PolicyKey = "MDM.Market";
var appSettings = new NameValueCollection();
appSettings["CacheItemPolicy.Expiration." + PolicyKey] = "8";
var configManager = new Mock<IConfigurationManager>();
configManager.Setup(x => x.AppSettings).Returns(appSettings);
ICacheItemPolicyFactory policyFactory = new AbsoluteCacheItemPolicyFactory(PolicyKey, configManager.Object);
var policyItem = policyFactory.CreatePolicy();
var marketName = "ABC market";
var marketKey = "Market-1";
var cache = new MemoryCache("MDM.Market");
cache.Add(marketKey, marketName, policyItem);
// Should get cache item
Assert.AreEqual(marketName, cache[marketKey]);
// Keep on accessing cache, it should expire approximately with in 10 iterations
int count = 0;
while (cache[marketKey] != null && count < 10)
{
count++;
Thread.Sleep(TimeSpan.FromSeconds(1));
}
Console.WriteLine("Cache has expired in {0} seconds:", count);
// should not be in the cache after configuratble time
Assert.IsNull(cache[marketKey]);
}
示例3: ShouldCreateAbsoluteCacheItemPolicyBasedOnTheConfiguration
public void ShouldCreateAbsoluteCacheItemPolicyBasedOnTheConfiguration()
{
const string PolicyKey = "MDM.Market";
var appSettings = new NameValueCollection();
appSettings["CacheItemPolicy.Expiration." + PolicyKey] = "8";
var configManager = new Mock<IConfigurationManager>();
configManager.Setup(x => x.AppSettings).Returns(appSettings);
ICacheItemPolicyFactory policyFactory = new AbsoluteCacheItemPolicyFactory(PolicyKey, configManager.Object);
var policyItem = policyFactory.CreatePolicy();
var marketName = "ABC market";
var marketKey = "Market-1";
var cache = new MemoryCache("MDM.Market");
cache.Add(marketKey, marketName, policyItem);
// Should get cache item
Assert.AreEqual(marketName, cache[marketKey]);
// wait until the expiry time
Thread.Sleep(TimeSpan.FromSeconds(10));
// should not be in the cache
Assert.IsNull(cache[marketKey]);
}
示例4: TestBasic
public void TestBasic()
{
var memoryCache = new MemoryCache("Foo");
var policy = new CacheItemPolicy();
memoryCache.AddOrGetExisting("Pop", 123, DateTimeOffset.MaxValue);
memoryCache.AddOrGetExisting("Top", "Gun", DateTimeOffset.MaxValue);
memoryCache.Add("Pop", 12, DateTime.MaxValue);
Assert.AreEqual("Gun", memoryCache.Get("Top"));
Assert.AreEqual(123, memoryCache.Get("Pop"));
}
示例5: TestCount
public void TestCount()
{
MemoryCache memoryCount = new MemoryCache("count");
Desenvolvedor dev = new Desenvolvedor();
dev.Nome = "Ninja";
dev.Linguagem = "C#";
dev.AnosExperiencia = 15;
CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(2);
memoryCount.Add("devRemove", dev, policy);
Assert.AreEqual(1, memoryCount.GetCount());
}
示例6: RedisNotificationBus_WhenInvalidation_ShouldDisposeMonitor
public void RedisNotificationBus_WhenInvalidation_ShouldDisposeMonitor()
{
var lcache = new MemoryCache(Guid.NewGuid().ToString());
var bus = new RedisNotificationBus("localhost:6379", new InvalidationSettings() { TargetCache = lcache, InvalidationStrategy = InvalidationStrategyType.ChangeMonitor });
bus.Connection = this.MockOfConnection.Object;
var monitor = new RedisChangeMonitor(bus.Notifier, "mykey");
lcache.Add("mykey", DateTime.UtcNow, new CacheItemPolicy() { AbsoluteExpiration = DateTime.UtcNow.AddDays(1), ChangeMonitors = { monitor } });
bus.Start();
//act
this.NotificationEmitter(Constants.DEFAULT_INVALIDATION_CHANNEL, "mykey");
//assert
Assert.False(lcache.Contains("mykey"));
Assert.True(monitor.IsDisposed);
}
示例7: when_reading_entity_then_rehydrates
public void when_reading_entity_then_rehydrates()
{
var newEvents = new IVersionedEvent[]
{
new TestEvent { SourceId = id, Version = 2, Foo = "Baz" }
};
var serialized = newEvents.Select(x => new EventData { Version = x.Version, Payload = Serialize(x) });
this.id = Guid.NewGuid();
var eventStore = new Mock<IEventStore>();
this.memento = Mock.Of<IMemento>(x => x.Version == 1);
var cache = new MemoryCache(Guid.NewGuid().ToString());
cache.Add("TestOriginatorEntity_" + id.ToString(), new Tuple<IMemento, DateTime?>(this.memento, null), DateTimeOffset.UtcNow.AddMinutes(10));
eventStore.Setup(x => x.Load(It.IsAny<string>(), 2)).Returns(serialized);
var sut = new AzureEventSourcedRepository<TestOriginatorEntity>(eventStore.Object, Mock.Of<IEventStoreBusPublisher>(), new JsonTextSerializer(), new StandardMetadataProvider(), cache);
var entity = sut.Find(id);
Assert.NotNull(entity);
Assert.Equal(id, entity.Id);
Assert.Equal(memento, entity.Memento);
Assert.Equal(newEvents, entity.History, new TestEventComparer());
}
示例8: TestCacheSliding
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, 1).ToString ();
config["__MonoTimerPeriod"] = 1.ToString ();
using (var mc = new MemoryCache ("TestCacheSliding", config)) {
Assert.AreEqual (0, mc.GetCount (), "#CSL1");
var cip = new CacheItemPolicy();
cip.SlidingExpiration = new TimeSpan (0, 0, 1);
mc.Add("slidingtest", "42", cip);
mc.Add("expire1", "1", cip);
mc.Add("expire2", "2", cip);
mc.Add("expire3", "3", cip);
mc.Add("expire4", "4", cip);
mc.Add("expire5", "5", cip);
Assert.AreEqual (6, mc.GetCount (), "#CSL2");
for (int i = 0; i < 50; i++) {
global::System.Threading.Thread.Sleep (100);
var item = mc.Get ("slidingtest");
Assert.AreNotEqual (null, item, "#CSL3-" + i);
}
Assert.AreEqual (1, mc.GetCount (), "#CSL4");
global::System.Threading.Thread.Sleep (4 * 1000);
Assert.AreEqual (0, mc.GetCount (), "#CSL5");
}
}
示例9: TestCacheExpiryOrdering
public void TestCacheExpiryOrdering ()
{
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, 1).ToString ();
config["__MonoTimerPeriod"] = 1.ToString ();
using (var mc = new MemoryCache ("TestCacheExpiryOrdering", config)) {
Assert.AreEqual (0, mc.GetCount (), "#CEO1");
// add long lived items into the cache first
for (int i = 0; i < 100; i++) {
var cip = new CacheItemPolicy ();
cip.SlidingExpiration = new TimeSpan (0, 0, 10);
mc.Add ("long-" + i, i, cip);
}
Assert.AreEqual (100, mc.GetCount (), "#CEO2");
// add shorter lived items into the cache, these should expire first
for (int i = 0; i < 100; i++) {
var cip = new CacheItemPolicy ();
cip.SlidingExpiration = new TimeSpan(0, 0, 1);
mc.Add ("short-" + i, i, cip);
}
Assert.AreEqual (200, mc.GetCount (), "#CEO3");
global::System.Threading.Thread.Sleep (4 * 1000);
Assert.AreEqual (100, mc.GetCount (), "#CEO4");
}
}
示例10: TestExpiredGetValues
public void TestExpiredGetValues ()
{
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, 10).ToString ();
config["__MonoTimerPeriod"] = 10.ToString ();
using (var mc = new MemoryCache ("TestExpiredGetValues", config)) {
Assert.AreEqual (0, mc.GetCount (), "#EGV1");
var keys = new List<string> ();
// add some short duration entries
for (int i = 0; i < 10; i++) {
var key = "short-" + i;
var expireAt = DateTimeOffset.Now.AddSeconds (1);
mc.Add (key, i.ToString (), expireAt);
keys.Add (key);
}
Assert.AreEqual (10, mc.GetCount (), "#EGV2");
global::System.Threading.Thread.Sleep (1000);
// we have waited but the items won't be expired by the timer since it wont have fired yet
Assert.AreEqual (10, mc.GetCount (), "#EGV3");
// calling GetValues() will expire the items since we are now past their expiresAt
mc.GetValues (keys);
Assert.AreEqual (0, mc.GetCount (), "#EGV4");
}
}
示例11: TestCacheShrink
public void TestCacheShrink ()
{
const int HEAP_RESIZE_THRESHOLD = 8192 + 2;
const int HEAP_RESIZE_SHORT_ENTRIES = 2048;
const int HEAP_RESIZE_LONG_ENTRIES = HEAP_RESIZE_THRESHOLD - HEAP_RESIZE_SHORT_ENTRIES;
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, 1).ToString ();
config["__MonoTimerPeriod"] = 1.ToString ();
using (var mc = new MemoryCache ("TestCacheShrink", config)) {
Assert.AreEqual (0, mc.GetCount (), "#CS1");
// add some short duration entries
for (int i = 0; i < HEAP_RESIZE_SHORT_ENTRIES; i++) {
var expireAt = DateTimeOffset.Now.AddSeconds (3);
mc.Add ("short-" + i, i.ToString (), expireAt);
}
Assert.AreEqual (HEAP_RESIZE_SHORT_ENTRIES, mc.GetCount (), "#CS2");
// add some long duration entries
for (int i = 0; i < HEAP_RESIZE_LONG_ENTRIES; i++) {
var expireAt = DateTimeOffset.Now.AddSeconds (12);
mc.Add ("long-" + i, i.ToString (), expireAt);
}
Assert.AreEqual (HEAP_RESIZE_LONG_ENTRIES + HEAP_RESIZE_SHORT_ENTRIES, mc.GetCount(), "#CS3");
// wait for the cache thread to expire the short duration items, this will also shrink the size of the cache
global::System.Threading.Thread.Sleep (5 * 1000);
Assert.AreEqual (HEAP_RESIZE_LONG_ENTRIES, mc.GetCount (), "#CS4");
// add some new items into the cache, this will grow the cache again
for (int i = 0; i < HEAP_RESIZE_LONG_ENTRIES; i++) {
mc.Add("final-" + i, i.ToString (), DateTimeOffset.Now.AddSeconds (4));
}
Assert.AreEqual (HEAP_RESIZE_LONG_ENTRIES + HEAP_RESIZE_LONG_ENTRIES, mc.GetCount (), "#CS5");
}
}
示例12: TestCacheSliding
public void TestCacheSliding ()
{
var config = new NameValueCollection ();
config["cacheMemoryLimitMegabytes"] = 0.ToString ();
config["physicalMemoryLimitPercentage"] = 100.ToString ();
config["pollingInterval"] = new TimeSpan (0, 0, 1).ToString ();
using (var mc = new MemoryCache ("TestCacheSliding", config)) {
Assert.AreEqual (0, mc.GetCount (), "#CSL1");
var cip = new CacheItemPolicy();
// The sliding expiration timeout has to be greater than 1 second because
// .NET implementation ignores timeouts updates smaller than
// CacheExpires.MIN_UPDATE_DELTA which is equal to 1.
cip.SlidingExpiration = new TimeSpan (0, 0, 2);
mc.Add("slidingtest", "42", cip);
mc.Add("expire1", "1", cip);
mc.Add("expire2", "2", cip);
mc.Add("expire3", "3", cip);
mc.Add("expire4", "4", cip);
mc.Add("expire5", "5", cip);
Assert.AreEqual (6, mc.GetCount (), "#CSL2");
for (int i = 0; i < 50; i++) {
global::System.Threading.Thread.Sleep (100);
var item = mc.Get ("slidingtest");
Assert.AreNotEqual (null, item, "#CSL3-" + i);
}
Assert.IsNull (mc.Get ("expire1"), "#CSL4-1");
Assert.IsNull (mc.Get ("expire2"), "#CSL4-2");
Assert.IsNull (mc.Get ("expire3"), "#CSL4-3");
Assert.IsNull (mc.Get ("expire4"), "#CSL4-4");
Assert.IsNull (mc.Get ("expire5"), "#CSL4-5");
Assert.AreEqual (1, mc.GetCount (), "#CSL4");
global::System.Threading.Thread.Sleep (4 * 1000);
Assert.IsNull (mc.Get ("slidingtest"), "#CSL5a");
Assert.AreEqual (0, mc.GetCount (), "#CSL5");
}
}
示例13: CreateCacheItemAndAdd
private static CacheItem CreateCacheItemAndAdd(MemoryCache target, string cacheKey, RedisChangeMonitor monitor = null)
{
var cacheItem = new CacheItem(cacheKey, DateTime.Now);
var policy = new CacheItemPolicy
{
AbsoluteExpiration = DateTime.UtcNow.AddDays(1)
};
if (monitor != null)
policy.ChangeMonitors.Add(monitor);
target.Add(cacheItem, policy);
return cacheItem;
}