【发布时间】:2019-09-28 11:58:13
【问题描述】:
为什么 DateTime.Subtract 有时会返回非常奇怪的值?
private ConcurrentDictionary<string, Request> _waitingList = new ConcurrentDictionary<string, Request>();
// send requests in thread #1 and set their SentAt time
_waitingList.TryAdd(macAddress, request);
request.SentAt = DateTime.UtcNow;
// then in a timer tick event in different thread every 5 seconds
private void OnTimerTick(object sender, ElapsedEventArgs e) {
foreach (var waiting in _waitingList) { // ConcurrentDictionary<string, Request>
var request = waiting.Value;
var msSinceSent = DateTime.UtcNow.Subtract(request.SentAt).TotalMilliseconds;
Debug.WriteLine($"sent *{request.Type}* {msSinceSent} ms ago");
}
}
sent *PackageUpdate* 336.2019 ms ago sent *PackageUpdate* 698.1145 ms ago sent *PackageUpdate* 1059.864 ms ago sent *PackageUpdate* 63693095680615.5 ms ago
最后一个值是巨大的,我经常得到这些,甚至无法理解这是怎么可能的。
【问题讨论】:
-
request.SentAt是什么数据类型? -
@DavidG 日期时间
-
你确定你使用的是
.Milliseconds而不是.TotalMilliseconds吗? -
@DavidG 是的,对不起,我正在使用 .TotalMilliseconds,我在最后一分钟刚刚更改了它。我已经用所有细节更新了我的问题,但没有太多。
标签: c# multithreading datetime timer