andrew4582

SeqentialGuidFactory

Mar 8th, 2012
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.24 KB | None | 0 0
  1.     public static class SeqentialGuidFactory {
  2.  
  3.         static long s_currentSequentialBase;
  4.         static long s_sequentialGuidCounter;
  5.  
  6.         static SeqentialGuidFactory() {
  7.             Random rnd = new Random(Guid.NewGuid().ToString().GetHashCode());
  8.             s_currentSequentialBase = rnd.Next();
  9.         }
  10.  
  11.         public static long CurrentSequentialBase {
  12.             get {
  13.                 if(s_currentSequentialBase <= 0)
  14.                     s_currentSequentialBase = new Random().Next();
  15.                 return s_currentSequentialBase;
  16.             }
  17.             set { s_currentSequentialBase = value; }
  18.         }
  19.  
  20.         public static Guid Create() {
  21.  
  22.             var ticksAsBytes = BitConverter.GetBytes(s_currentSequentialBase);
  23.  
  24.             Array.Reverse(ticksAsBytes);
  25.             var increment = System.Threading.Interlocked.Increment(ref s_sequentialGuidCounter);
  26.             var currentAsBytes = BitConverter.GetBytes(increment);
  27.  
  28.             Array.Reverse(currentAsBytes);
  29.  
  30.             var bytes = new byte[16];
  31.             Array.Copy(ticksAsBytes,0,bytes,0,ticksAsBytes.Length);
  32.             Array.Copy(currentAsBytes,0,bytes,8,currentAsBytes.Length);
  33.             return new Guid(bytes);
  34.         }
  35.  
  36.     }
Advertisement
Add Comment
Please, Sign In to add comment