How to Increment timer asynchronously ?

此生再无相见时 提交于 2019-12-13 06:20:47

问题


I am trying to Update a timer asynchronously On a Button Click .

say example i have set the time = 60 seconds

and when i run the program after few TIME the timer has reached to 45 seconds and when i click the Button ,then it should add j=15 seconds to the time and the timer should change to 60 seconds asynchronously. Please Help

    private int time = 60;
    DateTime dt = new DateTime();
    private j = 15 ;
    private DispatcherTimer timer;

    public MainWindow()
    {
        InitializeComponent();
        timer = new DispatcherTimer();
        timer.Interval = new TimeSpan(0, 0, 1);
        timer.Tick += timer_tick;
        timer.Start();
        }

    void timer_tick(object sender, EventArgs e)
    {
        if (time >0)
        {
          time--;
            text.Text = TimeSpan.FromSeconds(time).ToString();
        }
        else
        {
            timer.Stop();
        }
    }

  private void Button_Click(object sender, RoutedEventArgs e)
    {
        text.Text = dt.AddSeconds(j).ToString("HH:mm:ss");
    }

回答1:


Here is my code you can try it it's working.

    private int time = 60;
    DateTime dt = new DateTime();
    private int j = 15;
    private Timer timer1 = new Timer();


    void timer_tick(object sender, EventArgs e)
    {
        if (time > 0)
        {
            time--;
            text.Text = TimeSpan.FromSeconds(time).ToString();
        }
        else
        {
            timer1.Stop();
        }
    }

    public timer()
    {
        InitializeComponent();
        timer1 = new Timer();
        timer1.Interval = 1000;
        timer1.Tick += timer_tick;
        timer1.Start();
    }



    private void button1_Click(object sender, EventArgs e)
    {
        time += j;
    }


来源:https://stackoverflow.com/questions/21578147/how-to-increment-timer-asynchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!