Random.cs 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. // Copyright (c) .NET Foundation. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  3. // Copyright (c) .NET Foundation. All rights reserved.
  4. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  5. using System;
  6. using System.Runtime.CompilerServices;
  7. using System.Threading;
  8. namespace Benchmarks.Data
  9. {
  10. public class ConcurrentRandom
  11. {
  12. private static int nextSeed = 0;
  13. // Random isn't thread safe
  14. [ThreadStatic]
  15. private static Random _random;
  16. private static Random Random => _random ?? CreateRandom();
  17. [MethodImpl(MethodImplOptions.NoInlining)]
  18. private static Random CreateRandom()
  19. {
  20. _random = new Random(Interlocked.Increment(ref nextSeed));
  21. return _random;
  22. }
  23. public int Next(int minValue, int maxValue)
  24. {
  25. return Random.Next(minValue, maxValue);
  26. }
  27. }
  28. }