使用线程安全联锁日期时间更新。* [英] Thread safe DateTime update using Interlocked.*
问题描述
我可以使用互锁。*同步方式更新日期时间变量?
我希望保持在内存中的最后接触时间戳记。多个HTTP线程将更新的最后一抹日期时间变量。
我明白,日期时间变量是被替换,而不是更新的值类型。
我可以想出最好是持有时间戳总蜱在很长
类X
{
长_lastHit;
无效触摸()
{
Interlocked.Exchange(REF _lastHit,DateTime.Now.Ticks);
}
}
是的, 你可以这样做。你最大的问题可能是DateTime.Ticks不仅具有约20毫秒的分辨率。所以,如果你保持一个 DateTime的最后一个
或长蜱
变量,它其实并不重要。但由于没有交易所的DateTime的过载,你需要使用长
。
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 );
}
}
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
.
这篇关于使用线程安全联锁日期时间更新。*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!