SafeRandom.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace ServiceStackBenchmark
  5. {
  6. internal sealed class SafeRandom
  7. {
  8. private static volatile SafeRandom instance;
  9. private static object syncRoot = new object();
  10. private static Random random;
  11. private SafeRandom()
  12. {
  13. random = new Random();
  14. }
  15. public int Next()
  16. {
  17. int result;
  18. lock (random)
  19. {
  20. result = random.Next();
  21. }
  22. return result;
  23. }
  24. public int Next(int maxValue)
  25. {
  26. int result;
  27. lock (random)
  28. {
  29. result = random.Next(maxValue);
  30. }
  31. return result;
  32. }
  33. public int Next(int minValue, int maxValue)
  34. {
  35. int result;
  36. lock (random)
  37. {
  38. result = random.Next(minValue, maxValue);
  39. }
  40. return result;
  41. }
  42. public static SafeRandom Instance
  43. {
  44. get
  45. {
  46. if (instance == null)
  47. {
  48. lock (syncRoot)
  49. {
  50. if (instance == null)
  51. {
  52. instance = new SafeRandom();
  53. }
  54. }
  55. }
  56. return instance;
  57. }
  58. }
  59. }
  60. }