Thread safe DateTime update using Interlocked.*

前端 未结 4 1019
生来不讨喜
生来不讨喜 2021-02-12 22:40

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

4条回答
  •  再見小時候
    2021-02-12 23:15

    My approach is not one of the best, but you can use a string var to store a formatted date and then parse it back into datetime:

    class x
    {
      string _lastHit;
    
      void Touch()
      {
        Interlocked.Exchange( ref _lastHit, DateTime.Now.ToString("format your date") );   
      }
    }
    

    When you need to use this value, just parse into DateTime:

    DateTime.Parse(_lastHit)
    

    The parsing is always working, because the string is formatted using the DateTime class, but you can use TryParse to handle possible parsing errors

提交回复
热议问题