public void CanCreateWithCacheNameAndInstanceName() { var cache = new SimpleInmemoryCache("SomeCache.Instance1"); Assert.That(cache.Id.Name, Is.EqualTo("SomeCache"), "CacheName"); Assert.That(cache.Id.InstanceName, Is.EqualTo("Instance1"), "InstanceName"); }
public void Demo_SimpleInmemoryCache_within_single_thread_constructor_called_only_once() { var cache = new SimpleInmemoryCache(); int ctorCallCount = 0; Func <string, int> ctor = _ => { Interlocked.Increment(ref ctorCallCount); return(ctorCallCount); }; cache.GetOrAdd("Key", ctor); cache.GetOrAdd("Key", ctor); Assert.That(ctorCallCount, Is.EqualTo(1)); }
Demo_SimpleInmemoryCache_two_threads_receiving_cache_misses_will_cause_constructor_to_be_run_twice() { var cache = new SimpleInmemoryCache(); int ctorCallCount = 0; Func <string, int> slowCtor = _ => { // slow down the first ctor call to ensure second thread always see the cache // as empty even though this ctor has been called to add the item Thread.Sleep(TimeSpan.FromMilliseconds(100)); Interlocked.Increment(ref ctorCallCount); return(ctorCallCount); }; Func <string, int> ctor = _ => { Interlocked.Increment(ref ctorCallCount); return(ctorCallCount); }; Task <int> t1 = Task.Run(() => cache.GetOrAdd("Key", slowCtor)); Task <int> t2 = Task.Run(() => cache.GetOrAdd("Key", ctor)); await Task.WhenAll(t1, t2); Assert.That(ctorCallCount, Is.EqualTo(2)); }