Generating Unique Numeric IDs using DateTime.Now.Ticks Generating Unique Numeric IDs using DateTime.Now.Ticks multithreading multithreading

Generating Unique Numeric IDs using DateTime.Now.Ticks


You just need to use a static variable that is incremented each time you want another unique value. You can make this thread safe and still very fast by using the Interlocked.Increment method...

// Declarationprivate static int safeInstanceCount = 0;// Usage{      ...      Interlocked.Increment(ref safeInstanceCount);      ...}


DateTime.Now is absolutely terrible for this purpose. At best, you'll have a resolution of 1 millisecond; at worst, 17 ms on NT and 1 second (!) on CE/Compact Framework.

Consider using Interlocked.Increment method for a fast, thread-safe counter.


Start with a per-thread ID (if multiple threads are originating the requests), concatenated with a per-thread counter (if each thread is expected to originate more than one request).