CacheStress.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Web.Caching;
  3. using System.Threading;
  4. /// <summary>
  5. /// Summary description for Class1.
  6. /// </summary>
  7. public class CacheStress
  8. {
  9. static int threads = 0;
  10. static int KeyStart = 0;
  11. static long SlidingWindow = 0;
  12. static bool UseAbsoluteTime = false;
  13. static int Modulo = 71;
  14. static Cache c;
  15. static SafeSum Sum = new SafeSum();
  16. /// <summary>
  17. /// The main entry point for the application.
  18. /// </summary>
  19. static void Main(string[] args)
  20. {
  21. if (args.Length < 2) {
  22. Console.WriteLine("Usage: CacheStress <#threads> <#millis> [UseAbsoluteTime]");
  23. return;
  24. }
  25. c = new Cache();
  26. threads = System.Int32.Parse(args[0]);
  27. SlidingWindow = System.Int64.Parse(args[1]);
  28. UseAbsoluteTime = (args.Length > 2);
  29. for (int i = 0; i < threads; i++)
  30. {
  31. Thread th = new Thread(new ThreadStart(RunCycle));
  32. th.Start();
  33. }
  34. int secs = 10;
  35. for (int j = secs; ;j += secs)
  36. {
  37. Thread.Sleep(1000 * secs);
  38. Console.WriteLine("Executed {0} transactions in {1} seconds", Sum.Value, j);
  39. }
  40. }
  41. static void RunCycle()
  42. {
  43. int n = Interlocked.Increment(ref KeyStart);
  44. for (int i = 1; ; i++) {
  45. try
  46. {
  47. string key = "stam" + n;
  48. object o2 = c.Get(key);
  49. if (o2 == null)
  50. {
  51. if (UseAbsoluteTime)
  52. c.Insert(key, 1, null, DateTime.Now.AddTicks(SlidingWindow), Cache.NoSlidingExpiration);
  53. else
  54. c.Insert(key, 1, null, Cache.NoAbsoluteExpiration, new TimeSpan(SlidingWindow));
  55. }
  56. n = (n * 2 + i) % Modulo;
  57. }
  58. catch (Exception e)
  59. {
  60. Console.WriteLine("Caught exception " + e.GetType().ToString() + ": " + e.Message + e.StackTrace);
  61. }
  62. if (i == 100)
  63. {
  64. Sum.Add(i);
  65. i = 0;
  66. }
  67. }
  68. }
  69. class SafeSum
  70. {
  71. public SafeSum()
  72. {
  73. _value = 0;
  74. }
  75. public int Value { get { lock(this) { return _value; } } }
  76. public void Add(int i) { lock(this) { _value += i; } }
  77. private int _value;
  78. }
  79. }