Timers

A timer calls a method after a delay, or every period, on a thread-pool thread. The callback must be fast, must not throw, and must not assume it runs alone: two ticks of a periodic timer can overlap if the callback is slower than the period. The two timers of this lesson are the thread-pool one and the asynchronous one.

System.Threading.Timer

The constructor takes the callback, a state object, the due time and the period. A period of Timeout.Infinite makes the timer fire once, which is the safe shape when the callback decides whether to continue:

var ticks = 0; var done = new ManualResetEventSlim(); Timer? timer = null; timer = new Timer(_ => { var tick = Interlocked.Increment(ref ticks); Console.WriteLine($"tick {tick}"); if (tick == 3) { timer!.Dispose(); done.Set(); return; } timer!.Change(10, Timeout.Infinite); }, null, 10, Timeout.Infinite); done.Wait(); Console.WriteLine($"ticks {ticks}");

dotnet run

tick 1
tick 2
tick 3
ticks 3

The timer fired after ten milliseconds, the callback printed the tick and armed the timer for another ten, and the third callback disposed the timer and released the main thread. The order of the lines is the order of the ticks, because one timer does not overlap itself: the callback of a due timer runs after the previous one returned.

A timer that arms itself

A period given to the constructor is the simple form, and it has a different guarantee: the callback of the next period is queued whether or not the previous one finished. A program whose work may take longer than the period uses Change at the end of the work, as the example does, and gets at most one pending callback. The cost is a Change call per tick; the gain is that two ticks never run at the same time on the same timer.

The state object of the constructor is passed to every callback. The example passes null and closes over its variables, which is shorter for a program whose timer lives until it exits; a timer that lives inside a class passes the instance and keeps the callback static.

PeriodicTimer

PeriodicTimer is the asynchronous one: instead of a callback, it returns a task from WaitForNextTickAsync, and the consumer awaits it in a loop:

var count = 0; using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(5)); while (await timer.WaitForNextTickAsync()) { count++; if (count == 3) { break; } } Console.WriteLine($"ticks {count}"); Console.WriteLine($"period {timer.Period.TotalMilliseconds}");

dotnet run

ticks 3
period 5

Three ticks, then the loop left. The wait is a task, so the loop does not hold a thread between ticks, which is what a background job in a service wants. WaitForNextTickAsync returns false when the timer is disposed while a wait is pending, which is how a clean shutdown ends the loop; the break here is the shorter path.

Disposal

Exercises

  1. Give the first timer a period of ten milliseconds and count how many ticks arrive before the program stops it.
  2. Stop a periodic timer from another task and see the loop end without a break.
  3. Throw inside a timer callback and read what the process does.
  4. Use a timer to print the elapsed seconds of a program five times.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. On which thread does a System.Threading.Timer callback run?

    Answer

    A thread-pool thread

    The callback is queued to the pool, so it must be short and thread-safe.

  2. What does a period of Timeout.Infinite mean?

    Answer

    The timer fires once and does not repeat

    The example re-arms with Change for each further tick.

  3. What does this program print? var count = 0; var done = new ManualResetEventSlim(); Timer? timer = null; timer = new Timer(_ => { count++; if (count == 2) { timer!.Dispose(); done.Set(); return; } timer!.Change(1, Timeout.Infinite); }, null, 1, Timeout.Infinite); done.Wait(); Console.WriteLine(count);

    Answer

    2

    The callback fires, re-arms once, and the second tick stops it.

  4. What does Timer.Change do?

    Answer

    Re-arms or stops the timer without creating a new one

    The example used it to schedule the next tick of a one-shot timer.

  5. What does this program print? var count = 0; using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(5)); while (await timer.WaitForNextTickAsync()) { count++; if (count == 3) break; } Console.WriteLine(count);

    Answer

    3

    The loop counts three ticks and breaks.

  6. What does WaitForNextTickAsync return?

    Answer

    A task that completes at the next tick, with false when disposed

    It is awaited in a loop, and disposal ends the loop with false.

  7. What does this program print? using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(5)); Console.WriteLine(timer.Period.TotalMilliseconds);

    Answer

    5

    The Period property returns the interval that was given.

  8. Why must a timer callback not throw?

    Answer

    The exception is unhandled on a pool thread and ends the process

    Nothing awaits the callback, so a throw reaches the top of the process.

  9. What does disposing a timer do to a callback that is already running?

    Answer

    Nothing, the callback finishes on its own

    Dispose prevents future callbacks, and the running one is left to finish.

  10. What does this program print? using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(5)); var count = 0; while (await timer.WaitForNextTickAsync()) { count++; if (count == 1) { timer.Dispose(); } } Console.WriteLine(count);

    Answer

    1

    The disposal ends the wait with false after the first tick.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev