我正在使用时间戳来临时命令我的程序中的并发更改,并要求更改的每个时间戳都是唯一的.但是,我发现简单地调用DateTime.Now是不够的,因为如果快速连续调用,它通常会返回相同的值.
我有一些想法,但没有任何事情让我觉得这是"最好的"解决方案.有没有一种方法可以保证每次连续调用都能产生一个独特的DateTime?
我应该为此使用不同的类型,也许是长整数?DateTime具有明显的优势,可以像实时一样轻松解释,不像增量计数器.
更新:这是我最终编写的一个简单的折衷解决方案,它仍然允许我DateTime用作我的临时密钥,同时在每次调用方法时确保唯一性:
private static long _lastTime; // records the 64-bit tick value of the last time
private static object _timeLock = new object();
internal static DateTime GetCurrentTime() {
lock ( _timeLock ) { // prevent concurrent access to ensure uniqueness
DateTime result = DateTime.UtcNow;
if ( result.Ticks <= _lastTime )
result = new DateTime( _lastTime + 1 );
_lastTime = result.Ticks;
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
因为每个滴答值只有一千万分之一秒,所以这种方法在每秒调用1000万次时会引入明显的时钟偏差(顺便说一句,它的执行效率足够高),这意味着它是完全可以接受我的目的.
这是一些测试代码:
DateTime start …Run Code Online (Sandbox Code Playgroud) 我有弹性簇,其中我的索引包含当前日期-例如:
example-idex-2016-07-26 --> exists
example-idex-2016-07-25 --> exists
example-idex-2016-07-24 --> doesn't exist (weekend)
...
Run Code Online (Sandbox Code Playgroud)
是否可以跨多个索引查询而忽略不存在的索引。例如,这WORKS:
return elastic.search({
index: [
"example-idex-2016-07-26",
"example-idex-2016-07-25"],
],
...
});
Run Code Online (Sandbox Code Playgroud)
而这会返回404:
return elastic.search({
index: [
"example-idex-2016-07-25",
"example-idex-2016-07-24"], //this doesn't exist
],
...
});
Run Code Online (Sandbox Code Playgroud)
我希望第二个示例仅从25日起返回文档。