I’m developing an app that starts a System.Threading.Timer which does some fairly rapid reading/writing to the serial port (every 100ms). The timer’s callback method looks something like this:-
if (_timerTaskRunning)
{
Debug.WriteLine("still running");
return;
}
_timerTaskRunning = true;
... do the serial write/read here ...
_timerTaskRunning = false;
The _timerTaskRunning flag is a safeguard to ensure that the delegate doesn’t run if the previous timer “cycle” hasn’t finished, i.e. it’s taking longer than 100ms.
When I first start the app I see around a dozen debug messages from the if statement. It’ll then settle down but I see another group of messages 7 or 8 seconds later. It settles down again, and every once in a while I’ll see a group of messages appear in varying numbers.
I’m assuming the first group of messages are caused by the timer delegate running slowly due to the app still starting up, objects/UI initialising, etc, etc, while subsequent messages are perhaps caused by garbage collection kicking in every so often and slowing things down? It’s not the serial port because I see the same behaviour with a “mock” serial port.
I’ve tried delaying the timer’s first run by a couple of seconds but it makes no difference – I still get a batch of debug messages for the first second or so after the timer starts. It’s not the end of the world skipping some of the timer tasks but it would be interesting to know what might be causing them. Is there anything I can do to investigate the cause further, e.g. would perfmon shed any light on things? I haven’t used it before so which counters would you suggest?
It sounds like you have a reentrancy problem. Basically your _timerTaskRunning isn’t working as a safeguard likely due to race conditions.
If you have multiple threads that can call start you will need to synchronize the calls to it.