views:

288

answers:

7

Folks,

I want to develop a long running windows service (it should be working without problems for months), and I wonder what is the better option here:

  1. Use a while(true) loop in the OnStop method
  2. Use a timer to tick each n seconds and trigger my code
  3. Any other options ?

Thanks Essam

+5  A: 

I wouldn't do #1.

I'd either do #2, or I'd spin off a separate thread during OnStart that does the actual work.

Joe
+3  A: 

Might be worth considering a scheduled task with a short interval. Saves writing a lot of plumbing code and dealing with the peculiarities of Windows Services timers.

Codebrain
A: 

The System.Threading.Timer class would seem appropiate for this sort of usage.

Noldorin
+5  A: 

Anything but #1
The services manager (or the user, if he's the one activating the controls) expects OnStart() and OnStop() to return in a timely fashion.
The way it's usually done is to start your own thread that keeps things running and ofcourse, listens to an event that might tell it to stop.

shoosh
+1 for the separate thread approach - that's the way to go!
marc_s
+1  A: 

I would NOT recommend #1.

What I’ve done in the past for the exact same scenario/situation is create a scheduled task that runs ever N seconds, kicks off a small script that simply does these 2 things: #1 checks for “IsAlreadyRunning” flag (which is read from the database) #2 If the flag is true, then the script immediately stops end exits. If the flag is false, the script kicks off a separate process (exe) in a new thread (which utilizes a service to perform a task that can be either very short or sometimes really long, depending on the amount of records to process). This process of course sets and resets the IsAlreadyRunning flag to ensure threads do not kick off actions that overlap. I have a service that's been running for years now with this approach and I never had any problems with it. My main process utilizes a web service and bunch of other things to perform some heavy backup operations.

Dinci Garrone
A: 

Is it doing a

1 clean up task, or

2 waking up and looking to see if needs to run a task

If it is something like #2, then using MSMQ would be more appropriate. With MSMQ task would get done almost immediately.

david valentine
+2  A: 

Don't mess with the service controller code. If the service wants to stop, you will only make matters worse by using #1. And BTW the service can always crash, in which case your while(true) won't help you a thing.

If you really want to have a "running windows service (it should be working without problems for months)", you'd better make sure your own code is properly and thoroughly tested using unit and integration tests before your run it as a service.

Igor Brejc