private void AppBarButton_Click(object sender, RoutedEventArgs e) // Stopwatch Start
{
timer = new Timer(new TimerCallback(MyMethod), TimerDisplay, 0, 1);
timer2 = new Timer(new TimerCallback(MyMethod_Current), CurrentTimerDisplay, 0, 1);
stopwatch.Start();
currentStopwatch.Start();
}
private async void MyMethod(object Displayblock)
{
ms = stopwatch.ElapsedMilliseconds;
TextBlock Bd = (TextBlock)Displayblock;
ss = ms / 1000; ms = ms % 1000;
mm = ss / 60; ss = ss % 60;
hh = mm / 60; mm = mm % 60;
dd = hh / 24; hh = hh % 24;
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Bd.Text = dd.ToString("00") + ":" + hh.ToString("00") + ":" + mm.ToString("00") + ":" + ss.ToString("00") + ":" + ms.ToString("000"); });
}
private async void MyMethod_Current(object Displayblock1)
{
ms1 = currentStopwatch.ElapsedMilliseconds;
TextBlock Bd1 = (TextBlock)Displayblock1;
ss1 = ms1 / 1000; ms1 = ms1 % 1000;
mm1 = ss1 / 60; ss1 = ss1 % 60;
hh1 = mm1 / 60; mm1 = mm1 % 60;
dd1 = hh1 / 24; hh1 = hh1 % 24;
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Bd1.Text = dd1.ToString("00") + ":" + hh1.ToString("00") + ":" + mm1.ToString("00") + ":" + ss1.ToString("00") + ":" + ms1.ToString("000"); });
}
private void AppBarButton_Click_2(object sender, RoutedEventArgs e) // Add Lap
{
if(LapStore.Text=="")
{
currentStopwatch.Restart(); // when I restart the second timer and pause theres a slight difference of milli seconds
Lap_Count++;
LapStore.Text += ("Lap" + " " + Lap_Count).ToString();
LapStore.Text += ("\n" + TimerDisplay.Text + "\n").ToString();
}
else
{
currentStopwatch.Restart();
Lap_Count++;
LapStore.Text += ("Lap" + " " + Lap_Count).ToString();
LapStore.Text += ("\n" + CurrentTimerDisplay.Text + "\n").ToString();
}
}
当我重新启动第二个计时器时,我没有任何区别。什么是避免这种情况的可能解决方案,因为当我添加一圈并暂停秒表并计算出以毫秒为单位的差异时。
答案 0 :(得分:2)
<强>更新强>:
我认为缺少的时间来自UI更新和按钮事件之间的延迟。你应该在按钮事件中花时间:
private void AppBarButton_Click_2(object sender, RoutedEventArgs e) // Add Lap
{
var elapsed = currentStopwatch.Elapsed;
currentStopwatch.Restart();
Lap_Count++;
LapStore.Text += ("Lap" + " " + Lap_Count).ToString();
LapStore.Text += ("\n" + elapsed.ToString("G") + "\n").ToString();
}
这种行为是正确的IMO:
currentStopwatch
已重置currentStopwatch
继续0.000秒,但stopwatch
仍在x.123秒继续=&GT;有一个123 ms的“偏移”。
P.S。:你为什么要自己计算,为什么不简单:
elapsed = stopwatch.Elapsed;
ms = elapsed.Milliseconds;
ss = elapsed.Seconds;
mm = elapsed.Minutes;
hh = elapsed.Hours;
dd = elapsed.Days;