.Net an Timers

Associate
Joined
10 Jul 2006
Posts
2,423
Just wanted to make sure I got my understanding correct.

If I have a single threaded application with 100 Timers (with an interval of 10seconds) in it, all using the same Elapsed event handler which takes 5 seconds to run the routine of. Essentially meaning there will be many timers running the same code at the same time.

It is my understanding that when a Timer elapses, its event handler is run on ANY thread in the Thread Pool of the .NET RUNTIME (not just the application).

What determines the thread pool size of the .NET runtime or does it grow if needs be.
 
From http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx

There is one thread pool per process. Beginning with the .NET Framework 4, the default size of the thread pool for a process depends on several factors, such as the size of the virtual address space. A process can call the GetMaxThreads method to determine the number of threads. The number of threads in the thread pool can be changed by using the SetMaxThreads method. Each thread uses the default stack size and runs at the default priority.

From that it looks like it's dynamic based on the number of processes you have running. But you can sepcify a size using the method if you need to.
 
Sorry, what I meant was the number of Threads in the pool, not the size of the pool.

Because if I have only one single threaded .NET application running, surely there is only one thread and all the timers will elapse on that single thread.
 
From http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx

Use a TimerCallback delegate to specify the method you want the Timer to execute. The timer delegate is specified when the timer is constructed, and cannot be changed. The method does not execute on the thread that created the timer; it executes on a ThreadPool thread supplied by the system.

So it is given a thread in the threadpool by the system. It would probably still stand that if you have 100 timers, the system would allocate 100 threads in the threadpool (dependent on memory).

The application sounds messy if you have 100 timers all using the same elapsed event handler. Depending on what you are doing in the event handler you could cause any number of problems with blocking, memory problems etc.

I guess it comes down to try it and see.
 
There's a good book which covers threading and parallelism in it's last chapters. He splits it down in to when using these to perform either compute bound or IO bound tasks then covers threading syncronisation and different types of locks and schedulers, also timers etc. Really good book that's worth getting.

CLR via C# 4th edition

He also links to a free download by MS that shows example code around threading and parallel stuff, there's some really cool classes buried in the ParallelsExtensionExtra part.

MS Parallel samples

If you make up a default console or windows app and write std sequential code then the core of this will run on one main thread. If you start to use Tasks and Timers you can end up using multiple threads, really depends on how you work with them and what you do.
 
If I have a single threaded application with 100 Timers (with an interval of 10seconds) in it, all using the same Elapsed event handler which takes 5 seconds to run the routine of. Essentially meaning there will be many timers running the same code at the same time.

Not unless you have 100 cores. Otherwise they will be time-sliced, even if 100 threads are allocated (highly unlikely). Any thread pool implementation is not going to create 100 threads unless this is ~ degree of parallelisation on the machine is (i.e., 100 logical cores available).

To be frank, it sounds like the design is wrong if you need 100 timers with same interval executing the same handler.

That said, a worker thread with a while() {} and some some sort of sleep/yield backoff logic (so you don't just burn a core in a busy loop) would do here.

Sleep (i.e, yield CPU) is not really evil unless (as mentioned) you use argument as a *true* time to sleep for; what do you think the task scheduler does?
 
Guess what it comes down to is the fact I don't know whether its best to use Timers or Threads here.

Because I could simply use a thread with a while loop and sleep.

Using Task (Task.Factory, if using c#. net 4.0 or above), you can simply encapsulate code in a Task (.net 4 makes it REALLY easy).

I'd go with a Task and have a while loop in there which exits/breaks when you exit the program. You may also need ReaderWriteLockSlim objects, to ensure data is correctly read/written to/from.

Also, don't forget that a multi threaded app can run on a single core machine (each thread is handled sequentially to give the illusion of multi-tasking).

And is there a particular reason why you are trying to stick everything on a single core/thread? I'd have thought that all programmers are now attempting to gravitate towards multi-threaded applications. You can create multiple threads and let the machine (and .NET) decide how it wants to handle the multiple threads.
 
Sleep is evil. You don't know if the thread will sleep for the correct amount of time and can't be sure when it will wake up. I don't recommend the use of sleep.

Can you give a more specific example of why sleep should be avoided?
I've used this many times without a single issue.

Thanks
 
Most of the time there are better options than calling Thread.Sleep but I guess it's handy to simulate work being done when testing :p They've actually removed the System.Threading.Thread namespace from windows 8 store app projects so things like Thread.sleep & join etc are all gone.

If you think about it though it makes sense, calling thread.sleep causes the current thread to block at this point. The thread can't go back to the threadpool to be used for anything else so if there's lots of other work to be done you'll cause a new thread to be created which costs resources, then when your sleeping thread stops sleeping it will force a context switch to come back alive. Also the sleep time isn't as accurate as a timer firing and asking the threadpool to queue a new work item.

If you just want to have a piece of code loop for a while with a delay in it you can do something like this as well in 4.5, because of the await it won't block, tasks are pretty composable.

while (!cancellationTokenSource.IsCancellationRequested)
{
// do some stuff
try
{
await Task.Delay(yourTimeSpan, cancellationTokenSource.Token);
}
catch (TaskCanceledException)
{
// no need to log, Task.Delay just throws on cancel
}
}
 
I think saying Thread.Sleep is "evil" is a bit extreme. It's a low level threading construct, yes. Before TPL came along there wasn't really an alternative in most situations. Other than perhaps a timer. But a timer is also a low level threading construct.

TPL is higher level and is the preferred approach for new projects. But please don't go back through perfectly good code just to rid it of Thread.Sleep's. It's not evil, it's just legacy... at least in the .NET world.
 
I'd have thought that all programmers are now attempting to gravitate towards multi-threaded applications.

You'd be surprised. Look at NodeJS, a gargantuan anti-pattern of concurrency magic based on the legacy pattern of "callbacks". And the community around actually think it's cool, elegant and modern.
 
Last edited:
You also do it where it makes sense, go and check out how Redis works :)

Ugh. I'd prefer not. Redis is like the retarded cousin of Riak. And not, presumably, because it uses thread sleeps. But because of the whole VM debacle and the fact that they gave up trying to solve the problem and have decided that its memory limit will now simply be matched against available RAM.
 
Last edited:
No it's just essentially single threaded for it's main part, and pretty damn quick at where it's strong as well.

It's an event loop which is fine. It's a message/event oriented architecture. It's not using the callbacks model as is so common in JS land.

It's quick because it keeps its entire database in memory. Just like Memcached.
 
Back
Top Bottom