我正在尝试使用以 8000 个滴答开始的 TimeSpan
创建一个间隔小于 1ms 的循环(1 个滴答 = 100ns,因此 8000 个滴答等于 0.8ms 或 800us):
private static void MeasureAutoResetEvent()
{
TimeSpan interval = new TimeSpan(8000L); // 800us
double elapsed = 0;
Stopwatch watch = new Stopwatch();
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
while (true)
{
watch.Restart();
autoResetEvent.WaitOne(interval);
watch.Stop();
elapsed = ResolveTicks(UoM.Microsecond, watch.ElapsedTicks);
Console.WriteLine(elapsed); // <- Does not writes ±800
}
}
UoM
enum 和 ResolveTicks()
方法定义如下:
public enum UoM
{
Second,
Millisecond,
Microsecond,
Nanosecond,
}
public static double ResolveTicks(UoM uom, long ticks)
{
return
uom == UoM.Millisecond ? ticks * 1e3 / Stopwatch.Frequency :
uom == UoM.Microsecond ? ticks * 1e6 / Stopwatch.Frequency :
uom == UoM.Nanosecond ? ticks * 1e9 / Stopwatch.Frequency :
ticks * 1 / Stopwatch.Frequency;
}
我正在使用 Stopwatch
来测量 autoResetEvent.WaitOne(interval);
使用的时间。但是,控制台的输出不会写入 ±800。有谁知道我上面的代码有什么问题?
最佳答案
这里的问题是 .WaitOne()
只能精确到 5 到 20 毫秒(一般来说)。
因此,当然,如果您尝试等待 800us,那将遥遥无期。
.WaitOne()
的分辨率由当前Windows Timer Resolution决定.
关于c# - 使用带有 TimeSpan 的 AutoResetEvent.WaitOne 创建迭代低于 1 毫秒的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39287684/