Function that creates a timestamp in c#

前端 未结 6 499
小蘑菇
小蘑菇 2020-11-30 19:25

I was wondering, is there a way to create a timestamp in c# from a datetime? I need a millisecond precision value that also works in Compact Framework(saying that since Date

6条回答
  •  自闭症患者
    2020-11-30 20:04

    If you want timestamps that correspond to actual real times BUT also want them to be unique (for a given application instance), you can use the following code:

    public class HiResDateTime
    {
       private static long lastTimeStamp = DateTime.UtcNow.Ticks;
       public static long UtcNowTicks
       {
           get
           {
               long orig, newval;
               do
               {
                   orig = lastTimeStamp;
                   long now = DateTime.UtcNow.Ticks;
                   newval = Math.Max(now, orig + 1);
               } while (Interlocked.CompareExchange
                            (ref lastTimeStamp, newval, orig) != orig);
    
               return newval;
           }
       }
    }
    

提交回复
热议问题