首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >dispatcherTimer不重新启动

dispatcherTimer不重新启动
EN

Stack Overflow用户
提问于 2022-07-24 18:29:44
回答 1查看 43关注 0票数 2

我在我的应用程序中实现了倒计时

代码语言:javascript
复制
private async void Window_Activated(object sender, WindowActivatedEventArgs args)
{       
  dispatcherTimer = new DispatcherTimer();
  dispatcherTimer.Tick += dispatcherTimer_Tick;
  dispatcherTimer.Interval = new TimeSpan(0,1,0);
  dispatcherTimer.Start();     
}

private void dispatcherTimer_Tick(object sender, object e)
{
  TimeSpan timeSpan = new TimeSpan(blockTime.Hours, blockTime.Minutes, blockTime.Seconds);

  if (timeSpan != TimeSpan.Zero)
  {
    timeSpan = timeSpan.Subtract(TimeSpan.FromMinutes(1));
    Countdown_TexBlock.Text = String.Format("{0}:{1}", timeSpan.Hours, timeSpan.Minutes);
    dispatcherTimer.Start();   
  }     
  else
  {
    dispatcherTimer.Stop();
  }
}

代码工作,但只有一次,例如,我把15分钟的阻塞时间(倒计时将运行的时间),在一分钟后,countdown.text将是0:14。

不应该用dispatcher.start()重新启动

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-24 20:10:20

在您发布的代码中,我没有看到blockTime变量在开始时被更改为任何其他值。这意味着,在dispatchTimer的每一个滴答中,timeSpan.Subtract表达式的值总是计算到相同的14分钟。在您的代码中,14分钟分配给一个本地可变值,在滴答结束时释放。这给出了dispatchTimer在没有发出Tick的情况下停止发布Tick的外观。

下面是我运行的工作原理(对于测试,我将分钟更改为秒,以便在合理的时间内观察到)。

代码语言:javascript
复制
public sealed partial class MainWindow : Window
{
    public MainWindow()
    {
        this.InitializeComponent();
        // Create the dispatch timer ONCE
        dispatcherTimer = new DispatcherTimer();
        dispatcherTimer.Tick += DispatcherTimer_Tick;
        dispatcherTimer.Interval = TimeSpan.FromSeconds(1);

        // This will restart the timer every
        // time the window is activated
        this.Activated += (sender, e) =>
        {
            startOrRestartDispatchTimer();
        };
    }

    private void startOrRestartDispatchTimer()
    {
        dispatcherTimer.Stop(); // If already running
        blockTime = TimeSpan.FromSeconds(15);
        Countdown_TexBlock.Text = blockTime.ToString();
        dispatcherTimer.Start();
    }

    private void DispatcherTimer_Tick(object sender, object e)
    {
        if (blockTime > TimeSpan.Zero)
        {
            blockTime = blockTime.Subtract(TimeSpan.FromSeconds(1));
            Countdown_TexBlock.Text = blockTime.ToString();
            if (blockTime == TimeSpan.Zero)
            {
                Countdown_TexBlock.Text = "Done";
                dispatcherTimer.Stop();
            }
        }
    }

    TimeSpan blockTime = TimeSpan.FromSeconds(15);

    private DispatcherTimer dispatcherTimer;

    // This will restart the timer when the button is clicked.
    private void buttonRestart_Click(object sender, RoutedEventArgs e) =>
        startOrRestartDispatchTimer();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73101014

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档