// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Threading; using Enyim.Caching; using Enyim.Caching.Configuration; using Enyim.Caching.Memcached; namespace Cache.Memcached.Concurrency { public class Program { private delegate void F(MemcachedClient cache); private static void Test1(MemcachedClient cache) { int? hot = (int?)cache.Get("hot"); hot = hot + 1; cache.Store(StoreMode.Set,"hot", hot); } private static void Test3(MemcachedClient cache) { while(true) { CasResult res = cache.GetWithCas("hot"); int? hot = res.Result; hot = hot + 1; if(cache.Cas(StoreMode.Replace, "hot", hot, res.Cas).Result) break; } } ////private static void Test4(MemcachedClient cache) ////{ //// cache.Increment("hot", 0, 1); ////} private static void Testn(MemcachedClient cache, int nrep, F action) { for(int i = 0; i < nrep; i++) { action(cache); } } private const int NTHREADS = 10; private const int NOPS = 10000; private static void Test(MemcachedClient cache, string lbl, F action) { DateTime dt1 = DateTime.Now; cache.Store(StoreMode.Set, "hot", 0); Thread[] t = new Thread[NTHREADS]; for(int i = 0; i < NTHREADS; i++) { t[i] = new Thread(() => Testn(cache, NOPS/NTHREADS, action)); } for(int i = 0; i < NTHREADS; i++) { t[i].Start(); } for(int i = 0; i < NTHREADS; i++) { t[i].Join(); } int? hot = cache.Get("hot"); DateTime dt2 = DateTime.Now; Console.WriteLine("{0} : {1} = {2} ({3} ms)", lbl, hot, NOPS, (int)((dt2 - dt1).TotalMilliseconds)); } public static void Main(string[] args) { MemcachedClientConfiguration cfg = new MemcachedClientConfiguration(); cfg.Protocol = MemcachedProtocol.Binary; cfg.AddServer("localhost:11211"); using(MemcachedClient cache = new MemcachedClient(cfg)) { Test(cache, "No handling", Test1); Test(cache, "Replace with check", Test3); // atomic increment does not work in 2.16 ////Test(cache, "Atomic increment", Test4); } } } }