none
Why am I getting duplicate RowKey with DateTime.UtcNow.Ticks?

    Question

  • I have a post table with username as PartitionKey and DateTime.UtcNow.Ticks as the RowKey, so I can get posts returned in chronological order.  Recently I tried to load a bunch of posts into the table manually by doing a loop to insert them, but it would fail some of the time while worked other times. 

    When I debug into it, it is actually because the RowKey it tried to insert already existed, in other words the DateTime.UtcNow.Ticks returned the same value as last time it looped through.  Now if I add a delay into the loop or change my RowKey to Ticks+Guid, then it'll work no problem.

    I don't know if other people also experienced this before or what do they do in this case?  I'm developing with sdk1.4, win7 but on a quad-core machine, could this be the reason the loop gives dup ticks?  And, does this happen in the azure production environment? 

    Thanks!

    Friday, June 10, 2011 5:14 PM

Answers

  • Hi ray247,

    > the DateTime.UtcNow.Ticks returned the same value as last time it looped through. Now if I add a delay into the loop or change my RowKey to Ticks+Guid, then it'll work no problem.

    This happens because tick is a time unit. A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond. However, the CPU is fast enough that it may execute multiple code lines in one tick. That is why you may get the same DateTime.UtcNow.Ticks value in a loop statement, because two loops are executed in one tick.

    > Does this happen in the azure production environment?

    Of course it happens on Azure and even any machines as CPU is very fast. Ticks+Guid is the solution for this.

    Please see DateTime.Ticks Property for more information.

    Thanks,


    Wengchao Zeng
    Please mark the replies as answers if they help or unmark if not.
    If you have any feedback about my replies, please contact msdnmg@microsoft.com.
    Microsoft One Code Framework
    • Marked as answer by ray247ray Monday, June 13, 2011 5:08 PM
    Monday, June 13, 2011 6:49 AM