C#精确延时

前段时间有个项目需要精确延时发送数据,在网上招了很久没有找到合适的,后来发现windows api可以满足需求精确延时,误差在微秒级别。

直接上代码,有需要的小伙伴可u一直接拿去使用:

using System.Runtime.InteropServices;


[DllImport("kernel32.dll")]
public extern static short QueryPerformanceCounter(ref long x);


[DllImport("kernel32.dll")]
public extern static short QueryPerformanceFrequency(ref long x);
}

public void sleep(double mSleepTime)
{
long stop_Value = 0;
long start_Value = 0;
long freq = 0;
double dfTime = 0;
QueryPerformanceMethd.QueryPerformanceFrequency(ref freq);
QueryPerformanceMethd.QueryPerformanceCounter(ref start_Value);

while ((mSleepTime - dfTime * 1000.000) > 0.0000001)
{
QueryPerformanceMethd.QueryPerformanceCounter(ref stop_Value);
dfTime = (double)(stop_Value - start_Value) / (double)(freq);
}
}

 

posted on 2022-07-18 15:04  向往蓝天的伟  阅读(441)  评论(0编辑  收藏  举报