A Stopwatch
is a better way to solve this**. For example:
Stopwatch spw = new Stopwatch();
int stepNo = 0;
while (!haltWork)
{
Thread.Sleep(100);
switch (stepNo)
{
case 0:
TalkToSerialPort1();
spw.Restart();
stepNo += 1;
break;
case 1:
if (spw.Elapsed.Hours >= 3)
{
TalkToSerialPort2();
spw.Restart();
stepNo += 1;
}
break;
case 2:
if (spw.Elapsed.Hours >= 1)
{
TalkToSerialPort3();
spw.Restart();
stepNo += 1;
}
break;
// etc...
}
}
Here I've added a condition haltWork
- your main program will need some way to signal this thread to exit in a timely fashion if necessary. This runs the thread in a polling loop that will allow it to break and exit, supports user cancellation, and, because of the stopwatch, will provide you the precise time elapsed for the current step in the case of user cancellation that you can use for process diagnostics, restart procedures, etc.
The procedural process is broken up into steps using a switch
statement. This lets you perform long running procedural processes with waiting or polling steps in a clean and logical manner while also remaining responsive, able to provide active feedback (consider raising events periodically to alert the main thread of your current step, time elapsed, etc, for process logging purposes).
Note also that this example resets the stopwatch at each step - how you do this depends on your requirements; whether you need to control the interval between steps or whether it is more important to keep regular pace with respect to an arbitrary reference. If the latter, naturally just start the stopwatch once and make the rest of your intervals absolute rather than relative.
** I am proceeding from the assumption that doing this inside your C# application has been thought out carefully and that this is the best place to take responsibility for this task.
The windows task scheduler is one alternative place to handle repetitive "headless" tasks that need to be run at long intervals.
Another alternative, especially relevant to industrial control, is to use dedicated hardware to do this - a small PLC, etc.