- #1
Prof. 27
- 50
- 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;
}
}
}
}