forked from piranout/Funcular.IdGenerators
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConcurrentRandom.cs
54 lines (50 loc) · 1.46 KB
/
ConcurrentRandom.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
using System;
using System.Security.Cryptography;
using Funcular.ExtensionMethods;
namespace Funcular.IdGenerators
{
public static class ConcurrentRandom
{
[ThreadStatic]
private static Random _random;
private static readonly object _lock = new object();
private static long _maxRandom;
private static long _lastValue;
private static readonly RNGCryptoServiceProvider _rngCryptoServiceProvider;
static ConcurrentRandom()
{
_rngCryptoServiceProvider = new RNGCryptoServiceProvider();
}
public static long NextLong()
{
lock (_lock)
{
long value;
do
{
value = Random.NextLong(_maxRandom);
} while (value == _lastValue);
_lastValue = value;
return value;
}
}
public static Random Random
{
get
{
if (_random != null)
return _random;
var cryptoResult = new byte[4];
_rngCryptoServiceProvider.GetBytes(cryptoResult);
int seed = BitConverter.ToInt32(cryptoResult, 0);
_random = new Random(seed);
return _random;
}
}
public static long MaxRandom
{
get { return _maxRandom; }
set { _maxRandom = value; }
}
}
}