我有以下存储过程来检索新的日期时间:
CREATE PROCEDURE [dbo].[GetTransactionTime]
AS
BEGIN
SELECT [TransactionTime] = GetUTCDate()
END
在本地DB上使用一个简单的c#数据集来调用这个SP。
由于SQL的datetime精度为3.3ms,因此我必须等待至少3.3ms才能获得新的datetime。有关精度的更多信息,请访问msdn: http://msdn.microsoft.com/en-us/library/ms187819.aspx
在下面的例子中,我将等待5ms:
class Program
{
static void Main(string[] args)
{
var adapter = new SPTableAdapters.TransactionTimeTableAdapter();
do
{
GetTransactionTime(
new Func<DateTime>(() => { return (DateTime)adapter.GetTransactionTimeNOW(); })
);
} while (true);
}
public static DateTime lastTransactionTime = DateTime.MinValue;
private static bool IsTransactionTimeUnique(DateTime newTransactionTime)
{
if (newTransactionTime > lastTransactionTime)
{
lastTransactionTime = newTransactionTime;
return true;
}
return false;
}
public static void GetTransactionTime(Func<DateTime> funcGetTransactionTime)
{
DateTime newTransactionTime = funcGetTransactionTime();
//MSSQL datetime has a off 3.33ms; try 5ms
DateTime now = DateTime.UtcNow;
DateTime max = now.AddMilliseconds(5);
while (!IsTransactionTimeUnique(newTransactionTime))
{
DateTime backup = DateTime.UtcNow;
if (backup > max) //if we tried more than 5ms.
{
//Always try once again.
newTransactionTime = funcGetTransactionTime();
if (IsTransactionTimeUnique(newTransactionTime))
{
break;
}
Console.WriteLine("FAILED: Old datetime: " + lastTransactionTime.ToBinary() + " New datetime: " + newTransactionTime.ToBinary() + "Start: " + now.Millisecond + " End: " + backup.Millisecond + " Max: " + max.Millisecond);
return; ;
}
newTransactionTime = funcGetTransactionTime();
}
Console.WriteLine("OK!");
}
}
输出:FAILED: Old: 487 New: 487 Start: 479 End: 484 Max: 484
FAILED: Old: 487 New: 487 Start: 484 End: 489 Max: 489
FAILED: Old: 487 New: 487 Start: 489 End: 494 Max: 494
OK!
FAILED: Old: 503 New: 503 Start: 495 End: 500 Max: 500
FAILED: Old: 503 New: 503 Start: 500 End: 505 Max: 505
OK!
FAILED: Old: 517 New: 517 Start: 510 End: 515 Max: 515
FAILED: Old: 517 New: 517 Start: 515 End: 520 Max: 520
FAILED: Old: 517 New: 517 Start: 520 End: 525 Max: 525
OK!
FAILED: Old: 533 New: 533 Start: 526 End: 531 Max: 531
FAILED: Old: 533 New: 533 Start: 531 End: 536 Max: 536
OK!
FAILED: Old: 550 New: 550 Start: 541 End: 546 Max: 546
FAILED: Old: 550 New: 550 Start: 546 End: 551 Max: 551
FAILED: Old: 550 New: 550 Start: 551 End: 556 Max: 556
OK!
MSSQL不会每5ms给我一个唯一的日期时间,将5ms更改为20ms工作,但我不明白为什么5ms不工作。希望有人能澄清一下。
这里有几篇关于这个主题的文章,但基本上Windows时间更新的频率比每3.3ms更新一次要低。
http://www.grahamwideman.com/gw/tech/dataacq/wintiming.htmhttp://discuss.fogcreek.com/joelonsoftware/default.asp?cmd=show& ixPost = 85520
还有一篇关于GetTickCount精度的msdn文章:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms724408 (v = vs.85) . aspx
Windows仅以约50ms的周期更新当前日期/时间。