gpt4 book ai didi

c# - 使用 DispatchTimer 获得 1 毫秒精度的运行时间

转载 作者:太空狗 更新时间:2023-10-29 23:03:41 29 4
gpt4 key购买 nike

我正在尝试使用调度计时器测量按键事件之间耗时(以毫秒为单位),但是当声明调度计时器具有 1 毫秒的间隔然后建立滴答事件时,它不会每 1 毫秒触发一次,而是在某处触发像 10-100 毫秒(猜测)。如果此滴答事件未按时触发,我如何以毫秒为单位准确测量时间?我在似乎无法访问 System.Timers 的 silverlight 中执行此操作。 System.Threading.Timer 似乎也会发生同样的情况。

这是代码的基础:

public void StartTimer(object o, RoutedEventArgs sender)
{
System.Windows.Threading.DispatcherTimer myDispatcherTimer = new
System.Windows.Threading.DispatcherTimer();
myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1); // 1 Milliseconds
myDispatcherTimer.Tick += new EventHandler(Each_Tick);
myDispatcherTimer.Start();
}

// A variable to count with.
int i = 0;

public void Each_Tick(object o, EventArgs sender)
{
i++;
}

public void keypress(object s, EventArgs args)
{
label1.contents = i.ToString();
i = 0;
}

有什么想法吗?

最佳答案

开始Stopwatch取而代之的是每次按下一个键时,只需从上次经过的毫秒数(您需要将其存储在变量中)中减去秒表当前经过的毫秒数。

    private Stopwatch _stopwatch;
private int _lastElapsedMs;

public void StartTimer(object o, RoutedEventArgs sender)
{
_lastElapsedMs = 0;
_stopwatch = Stopwatch.StartNew();
}

public void keypress(object s, EventArgs args)
{
int elapsedMs = (int)_stopwatch.ElapsedMilliseconds;
int currentElapsed = (elapsedMs - _lastElapsedMs);

_lastElapsedMs = elapsedMs;

label1.contents = currentElapsed.ToString();
}

关于c# - 使用 DispatchTimer 获得 1 毫秒精度的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4251644/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com