Search code examples
c#performancetimer

How expensive is Timer.Change?


Consider a server with a performance-sensitive, highly-parallel, C# processing pipeline where we want to raise an event if something stops happening, e.g. the flow of media.

One theorized approach is to create a timer that is delayed continuously by the pipeline. By way of a simplistic example:

const int IDLE_MILLIS = 1000; // 1 second

Timer timer = new Timer(IDLE_MILLIS, () =>
{
   Console.WriteLine("Pipeline is idle.");
});

void ProcessMediaFrame(MediaFrame frame)
{
    timer.Change(IDLE_MILLIS, Timeout.Infinite);

    // pipeline is not idle
}

How expensive is the Change method here? (https://learn.microsoft.com/en-us/dotnet/api/system.threading.timer.change)

Does the Timer consume any resources while idle?


Solution

  • The performance note in the source code (thanks Codexer for linking the correct file) says your case is exactly what they've optimized for.

    We assume that timers are created and destroyed frequently, but rarely actually fire.

    ...

    • timeouts for operations ... almost never fire, because the whole point is that the timer only fires if something has gone wrong.