简体   繁体   中英

Long running Windows Services

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

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.

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.

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 .

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.

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.

System.Threading.Timer类似乎适合这种用法。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM