Timers
System.Threading.Timer calls a method at a scheduled time or on a repeating interval. Use it for periodic background work — polling a sensor every second, blinking an LED, refreshing a UI element — without writing a dedicated thread.
NuGet package: GHIElectronics.TinyCLR.Core (System.Threading.Timer is in the core).
Periodic timer
The example below waits 3 seconds, then calls Ticker once a second forever:
using System.Diagnostics;
using System.Threading;
void Ticker(object state) {
Debug.WriteLine("Hello!");
}
var timer = new Timer(Ticker, null, dueTime: 3000, period: 1000);
Thread.Sleep(Timeout.Infinite);
The constructor's third argument (dueTime) is the delay before the first call; the fourth (period) is the interval between calls. Use Timeout.Infinite for either to disable initial delay or stop repeating.
Timer vs Thread
A common alternative is a thread with Thread.Sleep at the end of a loop. The difference matters:
- A thread sleeping 1 second per loop runs every
(processing time + 1 second)— variable, drifts with workload. - A timer with 1 second period fires every 1 second on the dot, regardless of how long the previous invocation took.
Timer wins when you want predictable cadence. Thread wins when the work itself takes most of the budget and you just want to throttle the loop.
Keep timer callbacks fast. If your timer fires every 100 ms but the callback takes 150 ms to run, you'll flood the system — invocations queue up and back-pressure builds. As a rule, timer callbacks should complete in much less time than the period.
One-shot timer
Pass Timeout.Infinite as the period to fire exactly once:
new Timer(Ticker, null, dueTime: 5000, period: Timeout.Infinite);
Changing or stopping a timer
Timer.Change(dueTime, period) reschedules a running timer; Dispose() stops it and releases the resource.
timer.Change(0, 500); // Restart immediately, 500 ms cadence.
timer.Change(Timeout.Infinite, Timeout.Infinite); // Stop firing without disposing.
timer.Dispose(); // Stop and release.