Search code examples
c#multithreadingdatetimelock-freeinterlocked

Thread safe DateTime update using Interlocked.*


Can I use an Interlocked.* synchronization method to update a DateTime variable?

I wish to maintain a last-touch time stamp in memory. Multiple http threads will update the last touch DateTime variable.

I appreciate that DateTime variables are value types that are replaced rather than updated.

The best I can come up with is to hold the timestamp as total ticks in a long

class x
{
  long _lastHit;

  void Touch()
  {
    Interlocked.Exchange(ref _lastHit, DateTime.Now.Ticks);
  }
}

Solution

  • Yes, you can do this. Your biggest problem may be that DateTime.Ticks only has a resolution of ~20 ms. So it doesn't really matter if you keep a DateTime last or a long ticks variable. But since there is no overload of Exchange for DateTime, you need to use long.