| | | 1 | | // Copyright (c) Microsoft. All rights reserved. |
| | | 2 | | // Licensed under the MIT license. See LICENSE file in the project root for full license information. |
| | | 3 | | |
| | | 4 | | namespace Microsoft.Azure.ServiceBus.Primitives |
| | | 5 | | { |
| | | 6 | | using System; |
| | | 7 | | |
| | | 8 | | internal static class ConcurrentRandom |
| | | 9 | | { |
| | | 10 | | // We lock on this when generating a seed for a threadLocalRandom |
| | | 11 | | [Fx.Tag.SynchronizationObject] |
| | 2 | 12 | | static readonly Random SeedGenerator = new Random(); |
| | | 13 | | |
| | | 14 | | [ThreadStatic] |
| | | 15 | | static Random threadLocalRandom; |
| | | 16 | | |
| | | 17 | | public static int Next(int minValue, int maxValue) |
| | | 18 | | { |
| | 68 | 19 | | return GetThreadLocalRandom().Next(minValue, maxValue); |
| | | 20 | | } |
| | | 21 | | |
| | | 22 | | // A 64-bit signed integer, x, such that 0 ≤ x ≤Int64.MaxValue. |
| | | 23 | | // This is different from ulong because ulong is 64 bits. |
| | | 24 | | // This only makes use of 63 bits - because it always returns positives |
| | | 25 | | public static long NextPositiveLong() |
| | | 26 | | { |
| | 0 | 27 | | var buffer = new byte[8]; |
| | 0 | 28 | | GetThreadLocalRandom().NextBytes(buffer); |
| | 0 | 29 | | var ulongValue = (long)BitConverter.ToUInt64(buffer, 0); |
| | 0 | 30 | | return Math.Abs(ulongValue); |
| | | 31 | | } |
| | | 32 | | |
| | | 33 | | static Random GetThreadLocalRandom() |
| | | 34 | | { |
| | 68 | 35 | | if (threadLocalRandom == null) |
| | | 36 | | { |
| | | 37 | | int seed; |
| | 10 | 38 | | lock (SeedGenerator) |
| | | 39 | | { |
| | 10 | 40 | | seed = SeedGenerator.Next(); |
| | 10 | 41 | | } |
| | | 42 | | |
| | 10 | 43 | | threadLocalRandom = new Random(seed); |
| | | 44 | | } |
| | | 45 | | |
| | 68 | 46 | | return threadLocalRandom; |
| | | 47 | | } |
| | | 48 | | } |
| | | 49 | | } |