I'm rather new to .Net development.
I have the following scenario: In my company we have machines that register cycle times (how long does the machine take to make 1 product). I have created a console application in .Net 6.0 that captures these cycles that are sent from the machines (via OPC server). There are expected cycle times and when the current cycle is exceeding these expected times then my console app will register that. Here's where the issue occurs.
To know that the current cycle exceeds its expected times I start a System.Timer when a cycle ended. If the cycle exceeds its expected times by 25% the timer's elapsed event is fired. The smallest interval I have in my timers is 150 seconds. Each machine has its own timer variable.
When the elapsed event is fired I want the timer in question to STOP and not fire that event again in 150 seconds. However, the way it is setup now, the eventhandler is executed about 50+ times in 1ms. I used DateTime.Now in a field of the record that is registered by the eventhandler and they are all on the exact same time. Since my interval is 150 seconds I know my code isn't executed slower than the interval hit.
I extended the System.Timer so I could pass an object with the timer.
public class MachineTresholdTimer : System.Timers.Timer
{
public Machine currentMachine { get; set; }
}
This is the method I use to start a timer from a machine when a cycle is registered:
void StartTimerTreshold(MachineTresholdTimer machineTimer, decimal timePerPanel)
{
if (timePerPanel != 0)
{
if (machineTimer.Enabled) machineTimer.Stop();
machineTimer.Interval = (double)((timePerPanel * 1000) + 50000);
machineTimer.Elapsed += OnExceededTreshold;
machineTimer.AutoReset = false;
machineTimer.Start();
}
}
If the timer is still running from the previous cycle I stop it and restart it since this means the previous cycle ran between the expected cycle times.
Since the Timer's property AutoReset = false I expected the Timer to stop when the event is triggered, as per documentation.
The method that triggers the function to start the timers is defined as async. The timer's event handler is not async. Since I am still wrapping my head around asynchronous tasks I don't know if this could be a problem.
With all this said now, what occurs is the following:
My eventhandler is executed about 50+ times. I create a record by accessing my own API endpoint to register an error via a dataservice. All the functions of my dataservice are async tasks. Even though the timer's interval is 150+ seconds I get 50+ records registered in my database from 1 (as I would expect) elapsed event. I use DateTime.Now in my Console application to fill a field for the record and this is the results I get:

All on the exact same time. What am I missing here? Are Timers even the right tool to use in this scenario? Any tips or nudges in the right directions are most welcome.