// 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 StackExchange.Redis; namespace Cache.Redis.Concurrency { public class Program { private delegate void F(IDatabase cache); private static void Test1(IDatabase cache) { int? hot = (int?)cache.StringGet("hot"); hot = hot + 1; cache.StringSet("hot", hot); } private static void Test4(IDatabase cache) { cache.StringIncrement("hot", 1); } private static void Testn(IDatabase 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(IDatabase cache, string lbl, F action) { DateTime dt1 = DateTime.Now; cache.StringSet("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 = (int?)cache.StringGet("hot"); DateTime dt2 = DateTime.Now; Console.WriteLine("{0} : {1} = {2} ({3} ms)", lbl, hot, NOPS, (int)((dt2 - dt1).TotalMilliseconds)); } private const int CONCURRENCY_CACHE = 2; public static void Main(string[] args) { ConnectionMultiplexer con = ConnectionMultiplexer.Connect("localhost:6379"); IDatabase cache = con.GetDatabase(CONCURRENCY_CACHE); Test(cache, "No handling", Test1); // replace with check not supported by library Test(cache, "Atomic increment", Test4); } } }