Thread safe DateTime update using Interlocked.*

前端 未结 4 1020
生来不讨喜
生来不讨喜 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:34

    EDIT: based on comments below from @romkyns [Thanks]

    If your code is running on a 32 bit machine. then a 64 bit long is going to be written to memory in two atomic operations, which can be interrupted by a context switch. So in general you do need to deal with this issue.

    But to be clear, for this specific scenario, (writing a long value which represents time ticks) it could be argued that the problem is so very unlilely as to be not worth dealing with... since (except for a split second once every 2^32 ticks), the value in the high word (32 bits) will be the same for any two concurrent writes anyway... and even in the very unlikely event that there are two concurrent writes which span that boundary, which concurrently interrupt each other and you get the hi word from one and the low word from the other, unless you are also reading this value every millesecond, the next write will fix the issue anyway, and no harm would be done. Taking this approach, however, no matter how unlikely the bad case might be, still allows for the extremely slim but possible scenario of gettign a wrong value in there once in every 4 Billion ticks... (And good luck trying to reproduce that bug...)

    If you are running on a 64 bit machine, otoh, (much more likely at this point in time but not guaranteed) then the value in the 64 bit memory slot is written atomically, and you don't need to worry about concurrency here. A race condition (Which is what you are trying to prevent) can only occur if there is some program invariant that is in an invalid state during some block of processing that can be interrupted by another thread. If all you are doing is writing to the lastTouch DateTime variable (memory location) then there is no such invlaid invariant to be concerned with, and therefore you do not need to worry about concurrent access.

提交回复
热议问题