What is wrong with using DateTime.Now. as main part of Unique ID?

主宰稳场 提交于 2020-01-24 02:55:35

问题


I used to use RNGCryptoServiceProvider to generate string-based Order ID's, but, there were 4 instances where ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@$%^*()_- would generate an already-existing Order ID.

And it got me thinking...

Why can't we just use something like:

<html>
...
<p>@GenerateOrderId()</p>
...
</html>

and:

public string GenerateOrderId()
{
   return "OID" + 
      DateTime.Now.Year + DateTime.Now.Month +
      DateTime.Now.Day + 
      DateTime.Now.Hour + 
      DateTime.Now.Minute + 
      DateTime.Now.Second + 
      DateTime.Now.Millisecond;
}

I've been told that it's a bad idea, but without any explanation, or reason, it's still stuck in my head. ... The reason I'd like to use this, is because it will always be unique.


回答1:


Computers work at nanosecond speeds. You would be guaranteed to generate a duplicate order ID almost immediately.

Your best bet would be to use a GUID [MSDN-C#] [MSDN-SQL] (a.k.a. UNIQUEIDENTIFIER in the SQL world).




回答2:


It won't always be unique.

If the same process is carried out during the same millisecond, then it will be identical.

As @Bill has stated, you should use a GUID for a unique string.




回答3:


Never call the Now getter that many times. "Now" may change while you're adding the strings. You could say DateTime.Now.ToString("yyyyMMddHHmmssfff") or similar, but it's much better to use Guid.NewGuid() for this.




回答4:


If you just want a globally unique identifier and aren't bothered about the format, why don't you just use a GUID?

http://msdn.microsoft.com/en-us/library/system.guid.newguid.aspx

using System;

class Sample 
{
    public static void Main() 
    {
        Guid g = Guid.NewGuid();
        Console.WriteLine(g);
    }
}

It even has a type in T-SQL (which you may well be using given that you're using ASP.NET)




回答5:


I recommend letting your database handle that responsibility, but if you must do it in code, then use GUID. GUID has a low probability of being duplicated.

  public string GenerateOrderId()
  {
    return System.Guid.NewGuid().ToString();
  }



回答6:


Not to beat a dead horse, but your usage of DateTime.Now is of more concern than what you're trying to do. You can rewrite your method and achieve the same goal much more succinctly:

public string GenerateOrderID()
{
  return "OID" + DateTime.Now.Ticks.ToString();
}

I would still recommend using a Guid over this approach. However, 99% of the time, the Ticks property is going to give you a different number each time it's called.



来源:https://stackoverflow.com/questions/11849039/what-is-wrong-with-using-datetime-now-as-main-part-of-unique-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!