同一程序中有多个定时器

本文关键字:定时器 程序 | 更新日期: 2023-09-27 18:23:43

我正在尝试制作一个程序,其中有两个定时器,以不同的时间间隔运行。目前我有一个定时器工作良好,我需要有另一个运行。我的第一个定时器的代码看起来是这样的:

    private void startButton_Click(object sender, RoutedEventArgs e)
    {
        Random rand = new Random();
        int ranMin = rand.Next(1,24);
        int ranSec = rand.Next(0, 59);

        System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
        dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
        dispatcherTimer.Interval = new TimeSpan(0, ranMin, ranSec);
        dispatcherTimer.Start();
        min.Content = ranMin;
        sec.Content = ranSec;
        openP();
    }
    private void dispatcherTimer_Tick(object sender, EventArgs e)
    {
        **code for timer in here
    }

这很好,但现在我需要另一个计时器以1秒的间隔运行,使用不同的代码,当我试图通过将所有dispatcherTimer放入dispatchertime2来复制它时,我遇到了错误。

同一程序中有多个定时器

我不确定你在做什么(你应该发布错误),但以下内容适用于你提供的代码:

    private void startButton_Click(object sender, RoutedEventArgs e)
        {
            Random rand = new Random();
            int ranMin = rand.Next(1,24);
            int ranSec = rand.Next(0, 59);

            System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = new TimeSpan(0, ranMin, ranSec);
            dispatcherTimer.Start();
            // New timer
            System.Windows.Threading.DispatcherTimer dispatcherTimer2 = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer2.Tick += new EventHandler(dispatcherTimer2_Tick);
            dispatcherTimer2.Interval = new TimeSpan(0, 0, 1);
            dispatcherTimer2.Start();
            min.Content = ranMin;
            sec.Content = ranSec;
            openP();
        }
        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            //code for timer in here
        }
        private void dispatcherTimer2_Tick(object sender, EventArgs e)
        {
           //code for timer2 in here
        }