0

I'm creating in-memory local cache of a network filesystem.

I want every directory/file to have LastDownloadedTime attribute, and then compare it with current time to decide whether the directory/file is too old to be used from cache.

But I'm uncertain whether DateTime.Now() is what I need. What happens if the user changes system time? How can simestamps suitable for my task be obtained in .NET?

Andrey Moiseev
  • 3,914
  • 7
  • 48
  • 64

4 Answers4

1

Take a look at System.DateTime.UTCNow(). It'll return the UTC time. Just make sure you are consistently calling on both ends (when you store the cache as well as when you test it for expiration).

More info: https://msdn.microsoft.com/en-us/library/system.datetime.utcnow(v=vs.110).aspx

Chris Steele
  • 1,343
  • 1
  • 9
  • 20
0

You should use DateTimeOffset. According to the docs:

Uniquely and unambiguously identify a single point in time. The DateTimeOffset type can be used to unambiguously define the meaning of "now", to log transaction times, to log the times of system or application events, and to record file creation and modification times.

If your application is running on a user's machine, though, they could change their system time (as you mentioned). The only way to prevent that is to have your application ping a time server to get an authoritative timestamp.

Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
0

I think I'm going to use Stopwatch for timestamps, because my filesystem cache is in-memory, it does not survive system reboot. Timestamps are going to be relative to the start of the Stopwatch.

Though, Stopwatch is known to be buggy.

But I consider system clock-dependent solutions to be even more dangerous, as the user may set system clock to some date in the past, messing everything up.

Community
  • 1
  • 1
Andrey Moiseev
  • 3,914
  • 7
  • 48
  • 64
0

If you are staying within bounds of local server then DateTime.UtcNow is the most convenient option for the task. Yes, if user changes local time, then that will invalidate cache and trigger unnecessary update.

You will need to use NTP (time) servers to avoid that problem. So, instead of using local server UTC time, you will obtain UTC time from NTP server (there are plenty of them available around the world).

Please refer to NTP wikipedia article

Riad Baghbanli
  • 3,105
  • 1
  • 12
  • 20