Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there a possibility for this code to generate the same identity,

for (int i = 0; i < 20; i++)
    {
        string TransID = DateTime.Now.Ticks.ToString();
    }

What are the considerations that make this happen?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
532 views
Welcome To Ask or Share your Answers For Others

1 Answer

Yes, this code can generate the same identifier.

Regardless of the tick precision, it can do so if the system date is changed in Windows and/or the Bios.

And also if it is run by computers in different time zones or if you travel.

The latter case implies that you should absolutely not use such a code even in local and not-connected applications.

If you need ID for a personnal and local application, and you never travel, this code does what you want, but it is not recommended to use such bad pattern.

As everyone says, without being wrong, you should use Guid.New() which is actually the safest standard, or an int or a long auto-increment (for local or managed by a server) for a better performance in some cases.

https://docs.microsoft.com/dotnet/api/system.datetime.now

https://en.wikipedia.org/wiki/Unique_identifier

https://en.wikipedia.org/wiki/Universally_unique_identifier

How expensive is a GUID cast and comparison vs a string comparison


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...