Cache.Add absolute expiration - UTC based or not?

后端 未结 3 1485
伪装坚强ぢ
伪装坚强ぢ 2020-12-30 19:31

The examples for Cache.Add uses DateTime.Now.Add to compute the expiration, i.e. it passes:

 DateTime.Now.AddSeconds(60)

as th

3条回答
  •  余生分开走
    2020-12-30 19:56

    [Highly derivative of insights from Jeff Sternal's answer, which I've +1'd in incomplete payment :D]

    It seems that in 1.1 (didnt look at 1.0 but I assume its similar), in the absence of a DateTime.Kind and having published examples with a DateTime.Now-relative time, they feel comfortable immediately calling ToUniversalTime() immediately.

    Hence...

    1. in 1.x, you'll end up with a mess if you [the API user] use DateTime.UtcNow (and there's a sensitivity to DST starting during the call to Cache.Add)

    2. in 2.0 [and 3.x], you're safe to use either as long as the Kind on the time you supply is set [which it normally would be if you got the time from DateTime.Now or UtcNow]. [See Joe's comments and answer for full rationale] Definitely prefer UtcNow as ambiguity for 1 hour of DST switchover.

    3. The example stays as-is so people working against 1.x dont get misled [and people can go on pretending that DST is a wacky edge case :P]. [Ditto, as pointed out by Joe] But this is a very debatable stance as this can result in stuff staying in the cache for an extra hour.

    I'm still very interested to hear more details, including any from any Ponies out there.

    EDIT: I realise from Joe's comments that I didn't explicitly call out the fact that it is definitely more correct to use UtcNow if using 2.0 or later as one is exposed to risk of the item being cached for an extra hour during the DST 'groundhog hour'. I also think the MS doc should point this fact out (with the proviso that they need to mention that this does not to apply to 1.1 [regardless of whether the page is marked 2.0+ specific]. Thanks Joe.

    EDIT: Noda Time will have a neat wrapper to make this foolproof :D

提交回复
热议问题