Timer firing every second and updating GUI (C# Win

2020-01-20 02:28发布

问题:

I have a Windows Forms application where I need to have a timer working for 90 seconds and every second should be shown after it elapses, kind of like a stopwatch 1..2..3 etc, after 90 seconds is up, it should throw an exception that something is wrong.

I have the following code, but the RunEvent never fires.

        private void ScanpXRF()
        {
            bool demo = false;

            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();

            try
            {

                for (int timerCounter = 0; timerCounter < 90; timerCounter++)
                {
                    timer.Interval = 1000;
                    timer.Tick += new EventHandler(RunEvent);
                    timer.Start();

                    if(timerCounter == 89) {
                      throw new Exception(); 
                     }
                }

            }
            catch (Exception e)
            {
                timer.Dispose();
                MessageBox.Show("There is a problem!");                   
            }       
        }


          private void RunEvent(object sender, System.EventArgs e)
            {
                //boxStatus.AppendText("RunEvent() called at " + DateTime.Now.ToLongTimeString() + "\n");
                MessageBox.Show("timer fired!");
            }

Is there anything I am doing wrong here or are there other suggestions for other ways to achieve the same result?

回答1:

A timer needs to be declared at the form level, or else it may not be disposed of when the form closes:

System.Windows.Forms.Timer timer;
int counter = 0;

Your starting code should just start the timer:

private void ScanpXRF()
{
   counter = 0;
   timer = new System.Windows.Forms.Timer();
   timer.Interval = 1000;
   timer.Tick += RunEvent;
   timer.Start();
}

The RunEvent is your Tick event being called every second, so your logic needs to go in there:

private void RunEvent(object sender, EventArgs e)
{
  counter++;
  if (counter >= 90) {
    timer.Stop();
    // do something...
  }
}


回答2:

made it work

   private void ScanpXRF()
        {
            _pXRFTimerCounter = 0;
            pXRFTimer.Enabled = true;
            pXRFTimer.Interval = 1000;
            pXRFTimer.Elapsed += new ElapsedEventHandler(pXRFTimer_Tick);
            pXRFTimer.Start();
        }

        private static void pXRFTimer_Tick(Object sender, EventArgs e)
        {
            _pXRFTimerCounter++;

            if (_pXRFTimerCounter >= 90)
            {
                pXRFTimer.Stop();
                // do something...               
            }
            else
            {
                MessageBox.Show(_pXRFTimerCounter.ToString() + " seconds passed");
            }
        }

I made the timer

System.Timers