Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Unique Numeric IDs using DateTime.Now.Ticks

I need to generate a unique numeric ID to attach to an incoming request. This ID is used only temporarily to track the request and will be discarded once the request has completed processing. This ID will only be used in the context of this application but will need to be assigned in a high performance multi-threaded way.

I was thinking of using DateTime.Now.Ticks for this ID but would like to know if DateTime.Now.Ticks could still generate a colliding ID if simultaneous requests are being concurrently being processed?

If anyone could suggest a better way to generate these IDs (preferably one that is not Int64 like Tick is) in a multi-threaded environment, please let me know. Something as simple as an incrementing number would suffice even, if only I didn't have to lock the number before incrementing.

Thanks a lot for any help.

like image 828
shyneman Avatar asked Sep 28 '11 00:09

shyneman


People also ask

Are DateTime ticks unique?

This uses the DateTime. Now. Ticks property, which is “the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001”. It will therefore always be unique, unless the id is generated in a threaded scenario.

How to get unique timestamp in c#?

DateTime. Now. ToUniversalTime(). ToString( "yyyyMMddHHmmssf" );

What are ticks DateTime?

If the DateTime object has its Kind property set to Unspecified , its ticks represent the time elapsed time since 12:00:00 midnight, January 1, 0001 in the unknown time zone. In general, the ticks represent the time according to the time zone specified by the Kind property.


1 Answers

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...

// Declaration
private static int safeInstanceCount = 0;

// Usage
{
      ...
      Interlocked.Increment(ref safeInstanceCount);
      ...
}
like image 122
Phil Wright Avatar answered Oct 03 '22 15:10

Phil Wright