ConcurrentRandom.cs 762 B

12345678910111213141516171819202122232425262728293031
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.CompilerServices;
  4. using System.Text;
  5. using System.Threading;
  6. namespace PlatformBenchmarks
  7. {
  8. public class ConcurrentRandom
  9. {
  10. private static int nextSeed = 0;
  11. // Random isn't thread safe
  12. [ThreadStatic]
  13. private static Random _random;
  14. private static Random Random => _random ?? CreateRandom();
  15. [MethodImpl(MethodImplOptions.NoInlining)]
  16. private static Random CreateRandom()
  17. {
  18. _random = new Random(Interlocked.Increment(ref nextSeed));
  19. return _random;
  20. }
  21. public int Next(int minValue, int maxValue)
  22. {
  23. return Random.Next(minValue, maxValue);
  24. }
  25. }
  26. }