views:

338

answers:

2

What is the difference between having multiple Timers vs multiple Threads?

I have a Windows service that runs in the background. There are about ten "Sites" in a database that get loaded on init. Each site gets initialized in its own Timer object, and then the Timer executes code on an interval for each site. The code executed is from a static method in the main service class.

What happens when two timers are executing at the same time? Are they executing in the same process? Does a second timer have to wait for a first timer to exit the method before it can enter it? Is there any locking or race conditions to worry about?

Thanks for the insight.

A: 

I will assume that this is a .NET question.

Timers use the shared threads that are in the application's thread pool.

Multiple timer callbacks will execute concurrently, unless the thread pool has been exhausted of threads.

Compare this to using dedicated threads. The dedicated threads will always be available to execute code, but they tie up resources since they are not shared like the threads in the pool.

binarycoder
A: 

First off I think you need to realise there is a difference between Threads and Processes, a quick google came up with this

http://www.dotnetuncle.com/Difference/146_thread_process.aspx

Then within stack overflow was this quetion

http://stackoverflow.com/questions/729137/do-net-timers-run-asynchronously

So,

Timers on their own threads wont have to wait for the other timer to exit before they can run, because of this like anything multi-threaded, you will need to consider locking any reources which multiple timers use and there is the possibility of race condition.

Tetraneutron
Ya, I meant thread not process......so the part about "Timers on their own threads..." gets to the heart of the question...When you create new Timers, does .NET automatically run them in their own thread? According to binarycoder they DO run in the shared threadpool by default and you don't have to explicitly thread them.But I presume this means that you have to lock any code that you don't want accessed concurrently, even though there are no explicit threads created.
Exactly - Most .Net timers automticaly are run on their own thread from the thread pool and once somethings on its own thread - explicit or implicit - it will require the same care in regards to locking etc.
Tetraneutron