简体   繁体   中英

Generate a unique number without database

How do I generate a unique number in c# without the database?

(max 17 digits).

EDIT: digits only.

You could take a look at Twitter's open source Snowflake project for inspiration, which solves a similar problem. It's written in Scala, but a simplified version is quite simple to code in C#.

The premise is to get the current timestamp, and bitwise shift it left, leaving the right-hand bits available for a simple sequence number, which is reset to 0 every time the timestamp increments.

By playing around with the bit lengths, and altering the granularity of your timestamp (eg decide whether to use seconds or milliseconds), you should be able to produce something which can fit into 17 digits quite simply.

You can use GUID, A GUID (Globally unique identifier) is a 128-bit integer that can be used to uniquely identify something.

System.Guid.NewGuid()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM