我们常用的延迟代码函数如Sleep,Thread.Sleep函数,
但是它们只允许输入毫秒,,如果我们需求更高精度 如
纳秒(ns)/微秒(us)的延迟代码执行的时间 怎么去做呢?
在上图我们可以看见有这样一个传址参数
long duetime = -10 * us;
原参数类型为 LARGE_INTEGER
定义是用long而不是double
表示需要延迟的时间 它是以100纳秒为一单位
你给1表示100纳秒 是该函数可接最低时钟周期
CreateWaitableTimer // 创建可等待计时器
SetWaitableTimer // 启动可等待计时器
MsgWaitForMultipleObjects // 等待内核对象或消息
CloseHandle // 关闭内核对象
示例代码:
public static void Main(){UsDelay(5); // 5us}public static void UsDelay(int us){long duetime = -10 * us;int hWaitTimer = CreateWaitableTimer(NULL, true, NULL);SetWaitableTimer(hWaitTimer, ref duetime, 0, NULL, NULL, false);while (MsgWaitForMultipleObjects(1, ref hWaitTimer, false, Timeout.Infinite, QS_TIMER));CloseHandle(hWaitTimer);} [DllImport("kernel32.dll")] public static extern int CreateWaitableTimer(int lpTimerAttributes, bool bManualReset, int lpTimerName); [DllImport("kernel32.dll")] public static extern bool SetWaitableTimer(int hTimer, ref long pDueTime, int lPeriod, int pfnCompletionRoutine, // TimerCompleteDelegate int lpArgToCompletionRoutine, bool fResume); [DllImport("user32.dll")] public static extern bool MsgWaitForMultipleObjects(uint nCount, ref int pHandles, bool bWaitAll, int dwMilliseconds, uint dwWakeMask); [DllImport("kernel32.dll")] public static extern bool CloseHandle(int hObject); public const int NULL = 0; public const int QS_TIMER = 0x10;
不要惧怕黑暗,人间没有永恒的夜晚;不要担心严寒,