How to ensure a timestamp is always unique?

后端 未结 6 586
夕颜
夕颜 2020-12-01 00:18

I\'m using timestamps to temporally order concurrent changes in my program, and require that each timestamp of a change be unique. However, I\'ve discovered that simply call

6条回答
  •  心在旅途
    2020-12-01 00:51

    Er, the answer to your question is that "you can't," since if two operations occur at the same time (which they will in multi-core processors), they will have the same timestamp, no matter what precision you manage to gather.

    That said, it sounds like what you want is some kind of auto-incrementing thread-safe counter. To implement this (presumably as a global service, perhaps in a static class), you would use the Interlocked.Increment method, and if you decided you needed more than int.MaxValue possible versions, also Interlocked.Read.

提交回复
热议问题