-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathSafeRandom.cs
56 lines (47 loc) · 1.47 KB
/
SafeRandom.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
namespace Orleans.Runtime
{
/// <summary>
/// Thread-safe random number generator.
/// Has same API as System.Random but is thread safe, similar to the implementation by Steven Toub: http://blogs.msdn.com/b/pfxteam/archive/2014/10/20/9434171.aspx
/// </summary>
internal class SafeRandom
{
private static readonly RandomNumberGenerator globalCryptoProvider = RandomNumberGenerator.Create();
[ThreadStatic]
private static Random random;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Random GetRandom()
{
if (random == null)
{
byte[] buffer = new byte[4];
globalCryptoProvider.GetBytes(buffer);
random = new Random(BitConverter.ToInt32(buffer, 0));
}
return random;
}
public int Next()
{
return GetRandom().Next();
}
public int Next(int maxValue)
{
return GetRandom().Next(maxValue);
}
public int Next(int minValue, int maxValue)
{
return GetRandom().Next(minValue, maxValue);
}
public void NextBytes(byte[] buffer)
{
GetRandom().NextBytes(buffer);
}
public double NextDouble()
{
return GetRandom().NextDouble();
}
}
}