Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

c# - Can using Ticks of DateTime.Now can generate duplicates unique identifiers?

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...