System.Threading Multiple Timers in C#

  • Thread starter Thread starter Prof. 27
  • Start date Start date
  • Tags Tags
    Multiple
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 6K views
Prof. 27
Messages
49
Reaction score
1

Homework Statement


Basically I'm trying to create two timers using System.threading.timer that run in parallel. One that runs for a minute, one that runs for a second. When I run the program I get nonsensical output. Despite reading a lot of stack overflow questions I can't seem to find where I've gone wrong.

Homework Equations


None

The Attempt at a Solution


Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TimerTestFour
{
    class TimerState
    {
        public int counter = 0;
        public Timer tmr;
    }
    class Program
    {
        static void Main(string[] args)
        {
            TimerState s = new TimerState();
            TimerState t = new TimerState();

            TimerCallback timerDelegate = new TimerCallback(CheckStatus);
            TimerCallback timerDelegateTwo = new TimerCallback(CheckStatus);

            Timer timerS = new Timer(timerDelegate, s, 0, 60000);
            Timer timerT = new Timer(timerDelegateTwo, t, 0, 1000);

            s.tmr = timerS;
            t.tmr = timerT;

            while ((s.tmr != null) && (t.tmr != null))
            {
                Thread.Sleep(0);
                Console.WriteLine("Timers done.");
            }
        }
        static void CheckStatus(Object state)
        {
            TimerState z = (TimerState)state;
            z.counter++;
            Console.WriteLine("{0} Checking status {1}.", DateTime.Now.TimeOfDay, z.counter);
            if (z.counter == 1)
            {
                Console.WriteLine("Dispose Timer");
                z.tmr.Dispose();
                z.tmr = null;
            }
        }
    }
}
 
Physics news on Phys.org