Reputation: 341
I am trying to have an idea of how the System.Threading.Timer or a timer in .net really works in low level terms. What I am trying to get is a overview.
My doubt is, is the timer once executed, a thread or process always running, how it gets notified that the time finished, does it receive like an interrupt of the clock or PIT or something else?. If is not always running how will the time be correct if there is some time that maybe the thread or process is not running.
Upvotes: 1
Views: 265
Reputation: 171216
Using a thread would work but that's very inefficient.
Timers are just data structures. There's a .NET-side data structure and a kernel data structure. The kernels know how to notify a thread when some deadline is due. It's not necessary that a thread sits around and waits. (Simplifying this a bit.)
There's a .NET-based optimization layer that tries to create as little kernel timers as possible to make timers even cheaper. Basically, all timers are in a queue. There's a single kernel timer that elapsed when the earliest .NET timer elapses.
Timers are really cheap in effect.
Upvotes: 2
Reputation: 1
I dont know about its exact implementation but i would imagine it starts a new thread, logs the current system tickcount and sets up a loop where the starting tickcount is compared with the current tickcount. When it hits the set interval it raises an event, essentially a callback. At a low level its using a pointer to call a function outside of its scope.
The timer is not exact down to the millisecond. i think the resolution is about 15ms.
Im not fully confident if this is how its actually done so i hope you get some more answers.
Upvotes: 0