【问题标题】:Xaml C#, UWP Stopwatch delayXaml C#,UWP 秒表延迟
【发布时间】:2015-11-18 23:03:49
【问题描述】:

我正在尝试为 Windows 10 通用应用程序制作秒表功能。使用 DispatcherTimer 我已经能够得到一个可以工作的秒表,因为秒数最多为 60,触发分钟加 1,然后重置为零。秒数将继续递增,但当它重置为零时会有 1 秒的延迟。基本上,当它达到 60 时,秒数会重置为 0,下一秒会保持在 0,然后在下一秒上升到 1。有什么想法可能导致这种情况吗?非常感谢!

public sealed partial class MainPage : Page
{
    DispatcherTimer secondstimer = new DispatcherTimer();
    int secondscount = 0;

    int minutescount = 0;
    int hourscount = 0;

    public MainPage()
    {

        this.InitializeComponent();

        secondstimer.Interval = new TimeSpan(0, 0, 1);
        secondstimer.Tick += Secondstimer_Tick;

        SecondsTextBlock.Text = "00";
        MinutesTextBlock.Text = "00";
        HoursTextBlock.Text = "00";
    }

    private void Secondstimer_Tick(object sender, object e)
    {
        SecondsTextBlock.Text = secondscount++.ToString();

        if (secondscount == 61)
        {
            minutescount++;
            secondscount = 0;

            MinutesTextBlock.Text = minutescount.ToString();
            SecondsTextBlock.Text = secondscount.ToString();

        }
        if (minutescount == 61)
        {
            hourscount++;
            minutescount = 0;
            MinutesTextBlock.Text = minutescount.ToString();
            HoursTextBlock.Text = hourscount.ToString();
        }
    }
}

【问题讨论】:

  • 我在 60 岁时拥有它,但它会提前一秒

标签: c# xaml timer uwp stopwatch


【解决方案1】:

您也可以使用 StopWatch 类。

https://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch%28v=vs.110%29.aspx

var stopWatch = new StopWatch();
stopWatch.Start();

它会给你这样的经过时间

HoursTextBlock.Text = stopWatch.Elapsed.Hours.ToString();
MinutesTextBlock.Text = stopWatch.Elapsed.Minutes.ToString();
SecondsTextBlock.Text = stopWatch.Elapsed.Seconds.ToString();

【讨论】:

    【解决方案2】:

    您可以消除复杂性并不断计算秒数,然后像这样设置 TextBlock:

    HoursTextBlock.Text = (secondscount / 3600).ToString();
    MinutesTextBlock.Text = (secondscount % 3600) / 60).ToString();
    SecondsTextBlock.Text = (secondscount % 60).ToString();
    

    或类似的东西。希望这会有所帮助。

    【讨论】:

    • 是的!!!你是最棒的!非常感谢!现在按预期工作。知道为什么这会有所不同吗?
    • 很难说问题出在哪里,但这个计时器不是 100% 准确的,而且你的代码也不是线程安全的。
    • 再次感谢!有没有更好的方法来实现这一点?
    • 如果您想要更高的准确性,您可以读取每个回调中的 System.Environment.TickCount 值,并从中计算经过的秒数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    相关资源
    最近更新 更多