SoFunction
Updated on 2025-03-01

C# Guid length snowflake simple generator sample code

The standard long snowflake length is 64 bits, and it will waste 1 bits, then 41 bits of time, 10 bits of workid, 12 bits of sequence

Guid length 128 bits, 64 bits full time tick, 32 bit workid, 32 bit sequence, it can be said that it is very luxurious to use it casually

That is, the system can store random guids in some places, and some places can store snowflake guids, and change them at will.

Then there is a method to extract the time. Since it is a 64-bit full time, just take it out and transfer the time.

This class refers to other people's code. If you need to design a more complete guid snowflake, you can find the newid project on github or nuget. More complete methods written by foreigners

public class GuidSnowFlakeGenerator
 {
  readonly uint _c;
  int _a;
  int _b;
  long _lastTick;
  uint _sequence;

  SpinLock _spinLock;

  public GuidSnowFlakeGenerator(uint workId)
  {
   _spinLock = new SpinLock(false);
   _c = workId;
  }

  public Guid Next()
  {
   var ticks = ;

   int a;
   int b;
   uint sequence;

   var lockTaken = false;
   try
   {
    _spinLock.Enter(ref lockTaken);

    if (ticks > _lastTick)
     UpdateTimestamp(ticks);
    else if (_sequence == )
     UpdateTimestamp(_lastTick + 1);

    sequence = _sequence++;

    a = _a;
    b = _b;
   }
   finally
   {
    if (lockTaken)
     _spinLock.Exit();
   }

   var s = sequence;
   byte[] bytes = new byte[16];
   bytes[0] = (byte)(a >> 24);
   bytes[1] = (byte)(a >> 16);
   bytes[2] = (byte)(a >> 8);
   bytes[3] = (byte)a;
   bytes[4] = (byte)(b >> 24);
   bytes[5] = (byte)(b >> 16);
   bytes[6] = (byte)(b >> 8);
   bytes[7] = (byte)b;
   bytes[8] = (byte)(_c >> 24);
   bytes[9] = (byte)(_c >> 16);
   bytes[10] = (byte)(_c >> 8);
   bytes[11] = (byte)(_c);
   bytes[12] = (byte)(s >> 24);
   bytes[13] = (byte)(s >> 16);
   bytes[14] = (byte)(s >> 8);
   bytes[15] = (byte)(s >> 0);

   return new Guid(bytes);
  }


  void UpdateTimestamp(long tick)
  {
   _b = (int)(tick & 0xFFFFFFFF);
   _a = (int)(tick >> 32);

   _sequence = 0;
   _lastTick = tick;
  }

  public static DateTime GetTime(Guid guid)
  {
   var bytes = ();
   long tick = (long)bytes[0] << 56;
   tick += (long)bytes[1] << 48;
   tick += (long)bytes[2] << 40;
   tick += (long)bytes[3] << 32;
   tick += (long)bytes[3] << 24;
   tick += (long)bytes[3] << 16;
   tick += (long)bytes[3] << 8;
   tick += (long)bytes[3];
   return new DateTime(tick, );
  }
 }

The above is the detailed content of the sample code of the C# Guid length snowflake simple generator. For more information about the C# Guid Snowflake Generator, please pay attention to my other related articles!