Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How scalable is System.Threading.Timer?

I'm writing an app that will need to make use of Timers, but potentially very many of them. How scalable is the System.Threading.Timer class? The documentation merely say it's "lightweight", but doesn't explain further. Do these timers get sucked into a single thread (or very small threadpool) that processes all the callbacks on behalf of a Timer, or does each Timer have its own thread?

I guess another way to rephrase the question is: How is System.Threading.Timer implemented?

like image 608
Ben Collins Avatar asked Aug 28 '08 03:08

Ben Collins


People also ask

Is system timers timer multithreaded?

System. Timers. Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

Is system threading timer thread safe?

Timer is not thread-safe.

Does threading timer create a new thread?

Yes, it will create new threads.

How does system timer work?

Remarks. The Timer component is a server-based timer that raises an Elapsed event in your application after the number of milliseconds in the Interval property has elapsed. You can configure the Timer object to raise the event just once or repeatedly using the AutoReset property.


1 Answers

I say this in response to a lot of questions: Don't forget that the (managed) source code to the framework is available. You can use this tool to get it all: http://www.codeplex.com/NetMassDownloader

Unfortunately, in this specific case, a lot of the implementation is in native code, so you don't get to look at it...

They definitely use pool threads rather than a thread-per-timer, though.

The standard way to implement a big collection of timers (which is how the kernel does it internally, and I would suspect is indirectly how your big collection of Timers ends up) is to maintain the list sorted by time-until-expiry - so the system only ever has to worry about checking the next timer which is going to expire, not the whole list.

Roughly, this gives O(log n) for starting a timer and O(1) for processing running timers.

Edit: Just been looking in Jeff Richter's book. He says (of Threading.Timer) that it uses a single thread for all Timer objects, this thread knows when the next timer (i.e. as above) is due and calls ThreadPool.QueueUserWorkItem for the callbacks as appropriate. This has the effect that if you don't finish servicing one callback on a timer before the next is due, that your callback will reenter on another pool thread. So in summary I doubt you'll see a big problem with having lots of timers, but you might suffer thread pool exhaustion if large numbers of them are firing at the same timer and/or their callbacks are slow-running.

like image 179
Will Dean Avatar answered Oct 01 '22 10:10

Will Dean