DateTime.Now.Ticks repeating inside a loop

前端 未结 6 1107
小鲜肉
小鲜肉 2021-01-27 02:55

I am trying to generate a unique ID for the primary key of a table and I am using DateTime.Now.Ticks for it. That\'s a requirement for now we can\'t use Ident

6条回答
  •  走了就别回头了
    2021-01-27 03:50

    The only case where I see some merit in your strategy is if you need to query your database for data between specific dates. Otherwise a simple integer counter - starting from 0 or 1 - will probably always be better.

    Your idea is not utterly bad if implemented properly and used the way it is meant to be used. It may just be needlessly complicated.

    I am assuming that you want you primary key to be an increasing integer, a sensible requirement to keep your inserts fast with some databases. A GUID will not work for you. I am assuming that you cannot use an auto-incremented database key. I am also assuming that you will not write into your database from multiple applications - nor multiple computers.

    First, you need to take daylight saving into account: use DateTime.UtcNow instead of DateTime.Now. That's because DateTime.Now can jump backwards in case of daylight saving.

    Second, you should expect DateTime.UtcNow to jump backwards anyway in rare occasions - when the system clock is adjusted. It means you need to save the previously allocated value anyway.

    Third, as you already know, the precision of the system clock is not infinite - typically it is 15 ms -, so you need to save the previously allocated value and increment it in case DateTime.UtcNow returns the same value twice.

    Fourth, knowing that you will need to keep a variable holding the previously allocated value, why not drop the whole DateTime idea and rely only on that variable? What I mean is: at the start of your program, you could read the greatest value from the database, store it into your counter in memory and then increment the counter everytime you need a new key value.

提交回复
热议问题