I got a lot of interesting answers for the riddle, and here is my solution:private static int sequentialUuidCounter;
public static Guid CreateSequentialUuid()
{
var ticksAsBytes = BitConverter.GetBytes(DateTime.Now.Ticks);
Array.Reverse(ticksAsBytes);
var increment = Interlocked.Increment(ref sequentialUuidCounter);
var currentAsBytes = BitConverter.GetBytes(increment);
Array.Reverse(currentAsBytes);
var bytes = new byte[16];
Array.Copy(ticksAsBytes, 0, bytes, 0, ticksAsBytes.Length);
Array.Copy(currentAsBytes, 0, bytes, 12, currentAsBytes.Length);
return bytes.TransfromToGuidWithProperSorting();
} Basically, we use the current system ticks as the 1 – 8 bytes, and a counter incremented atomically on the 12 – 16 bytes. This ensures that even concurrent calls on the same tick will have a different value. Read more: Ayende @ Rahien
public static Guid CreateSequentialUuid()
{
var ticksAsBytes = BitConverter.GetBytes(DateTime.Now.Ticks);
Array.Reverse(ticksAsBytes);
var increment = Interlocked.Increment(ref sequentialUuidCounter);
var currentAsBytes = BitConverter.GetBytes(increment);
Array.Reverse(currentAsBytes);
var bytes = new byte[16];
Array.Copy(ticksAsBytes, 0, bytes, 0, ticksAsBytes.Length);
Array.Copy(currentAsBytes, 0, bytes, 12, currentAsBytes.Length);
return bytes.TransfromToGuidWithProperSorting();
} Basically, we use the current system ticks as the 1 – 8 bytes, and a counter incremented atomically on the 12 – 16 bytes. This ensures that even concurrent calls on the same tick will have a different value. Read more: Ayende @ Rahien
0 comments:
Post a Comment