-
Notifications
You must be signed in to change notification settings - Fork 0
/
SnowflakeIdGenerator.cs
48 lines (39 loc) · 1.14 KB
/
SnowflakeIdGenerator.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
namespace SnowflakeIdGeneratorForCSharp;
public sealed class SnowflakeIdGenerator
{
private long lastTimestamp = -1L;
private long sequence = 0L;
private readonly long workerId;
private readonly long datacenterId;
private readonly object lockObj = new object();
public SnowflakeIdGenerator(long workerId, long datacenterId)
{
this.workerId = workerId;
this.datacenterId = datacenterId;
}
public long CreateId()
{
lock (lockObj)
{
long timestamp = CurrentTimeMillis();
if(timestamp != lastTimestamp)
{
sequence = 0L;
}
if(sequence++ >= 4095)
{
while(timestamp <= lastTimestamp)
{
timestamp = CurrentTimeMillis();
}
}
lastTimestamp = timestamp;
long id = (timestamp << 22) | (datacenterId << 17) | (workerId << 12) | sequence;
return id;
}
}
private static long CurrentTimeMillis()
{
return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
}
}