Created
May 31, 2024 22:11
-
-
Save xk0fe/8bcd5bd19c18f4513e28dae78a3e87bd to your computer and use it in GitHub Desktop.
1,000,000 IDs per second for approximately 136 years
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Security.Cryptography; | |
using System.Text; | |
public class GuidGenerator | |
{ | |
private static readonly object LockObject = new object(); | |
private static int _sequenceNumber = 0; | |
private readonly string _serverId; | |
public GuidGenerator(string serverId) | |
{ | |
_serverId = serverId; | |
} | |
public string GenerateGuid() | |
{ | |
lock (LockObject) | |
{ | |
// Get current timestamp | |
long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); | |
// Increment sequence number | |
_sequenceNumber = (_sequenceNumber + 1) % 1000; // Example sequence within the same millisecond | |
// Generate random part | |
byte[] randomBytes = new byte[4]; | |
using (var rng = RandomNumberGenerator.Create()) | |
{ | |
rng.GetBytes(randomBytes); | |
} | |
string randomPart = BitConverter.ToString(randomBytes).Replace("-", ""); | |
// Combine parts | |
string guid = $"{timestamp}-{_serverId}-{_sequenceNumber:D3}-{randomPart}"; | |
return guid; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment