C# windows service does not always stop on shutdown - c#

I created a windows service with c# 2010. The problem is that when computer shuts down the service does not have time to stop and onstop is not always executing. I say not always because sometime it manages to stop. I have tried to use windows pre-shutdown notification that was introduced at vista, however the results are better but not absolute.
Is there anyway to get windows wait for my service to stop?
Is there anyway to change the order windows stops the services?

According to http://msdn.microsoft.com/en-us/library/windows/desktop/ms685149(v=vs.85).aspx, a service normally has about 20 seconds to shut down before the system gives up and shuts down anyway.
You might be able to send STOP_PENDING messages back if your service needs more time to shut down, but even then you're limited to about 125 seconds before the system figures you're never going to shut down, and pulls the rug out from under you.
In C#, you would have your service call RequestAdditionalTime during shutdown. Again, there's no guarantee that you'll get that extra time, but you can ask for it. Remember, though, if you ask for more time you better be done before that time expires, or you can ask for more. But eventually the system will shut you down (again, probably in less than 2 minutes).
In general, I've found that it's best if you construct your service so that you can shut it down quickly. If you can't shut down in a few seconds, you probably need to change your design.

This can be answer for you (and for somebody, who search same answer):
Why doesn't the RequestAdditionalTime() method work on restart in Vista/7?:
... Suppose Windows allows 13 seconds for all services to shutdown. Some other service takes 12 seconds of cpu time (so other services can't execute during that time) and finally shuts down. That leaves 1 second for all the rest. Windows is going to kill them.
This is the reason, why it sometimes shutdown correctly a sometimes doesn't.
By the way, Vista has 20 sec. to kill services, W7 has 12 sec. and W8 has 5 sec.

In your service class derived from ServiceBase, in override of OnStop you can request for additional time:
base.RequestAdditionalTime(1000 * 60 * 2);

Related

How window services work internally compared to task scheduler or task manager?

I am a .net developer working in web applications and from past few months I started working on windows applications and one application need to run every day at 12 noon so I wrote a web service with the help of google and it is working fine.
But I am just wondering how windows services work.
I read lot of posts and not one have answered my question.So coming forward in my own words.
According to my understanding in web service I create a scheduler using timer that runs all 24 hours and will execute the necessary code when the timer condition is met.
In scheduler I configure a scheduler that runs an application(which is a service in previous case) when the time condition is met.
Now my questions:
Regarding RAM usage?
I know services utilizes RAM. But considering if my code is heavy like lets consider 10mb. Ther fore .exe file will be around 10mb or more. So when service starts does it utilizes 10mb of RAM all 24 hours or it will just create just scheduler in service which will be pretty small and then loads service code when the time is met?
Considering scheduler how does it work. I think there will be a trigger that is fired when time is met and fired trigger will execute .exe file generically let me call it a service(but it is a application). So here the service code is separated from scheduler so only scheduler runs and loads service code into RAM.
Am I right?
Does scheduler also runs all 24 hours checking time?
If in case I have 2 services with one installer. Now there will be 2 servises installed. But I would like to know if both services is of 10mb each which makes 20 mb .exe size and when both services starts running does there sizes be of 10 mb each(considering it will lode relative service code) or 20 mb each(considering it will lode both service codes because they are in same exe).
Hoping for some valuable answered.
Thanks in advance.
Everything depends on your implementation.
This is how a windows service works:
Your installer registers a windows service object
The service object starts yourservice.exe
Within yourservice.exe you have to implement the service commands (e. g.: OnStart, OnStop)
Now it depends on you what to do in these methods
yourservice.exe runs as long as the service is running
My recommendations:
Pack your existing logic into a library
Start the timer in the service OnStart method (the timer needs almost no ressources)
In the timer callback instantiate your logic using the library (now your 10 megs are allocated)
Clean up everything after your work has been completed (the 10 megs get freed, if you don't use anything persistently)
In step 3 you are free to instantiate your logic twice which will use 2x 10 megs then, of course.

Detect unresponsive service process

I have a service daemon (running in Windows Server) that runs 24/7 (or it should) that I didn't write or have access to the source code.
For some unknown reason the service sometimes stops responding (my guess is that it deadlocks). This is a mail service so I know it has stopped working when I don't receive any mails from it in 'n' time (n is never fixed).
Currently the only programmatical way I can check if it's non-responsive is trying to stop the service, and if that times-out, I know it's dead/zombie. I can then force-kill the service process and just run the service again.
I want to automate this process (i.e., code a "watchdog"), and would like to periodically check if the service has stopped responding without trying to stop it first (I don't want to stop the service if it's really working).
Is there any programmatical way to check if a process is not responding which is not trying to stop it?
I don't have any clue how the service works internally so I can't just send a signal to it and wait for response (since I don't know what signals it would respond to, other than attempting to cleanly stop it).
This has been on and off in my head for some time and I haven't been able to find an answer.
If there's nothing else, I'd just make it stop every night or so (that'd be acceptable even if it's working), but if there's any way, I'd prefer to have some daemon check it every 10 minutes or so (stopping and restarting the service every 10 minutes would NOT be acceptable if it's working).
I'd appreciate any hints on where to look, if there's any.
PS: the code for service stopping, process killing or service starting is not a problem and I'm not looking for that... I'd only like a hint or direction on how to check if it has became non-responsive without knowing how it is programmed.

Get Notification when .EXE from task manager or in system Stopped using .NET technology

I have some windows application .exe which are run on my Domain server, i have a problem that if the .exe is stooped how can i get the notification that the .exe has stopped.
is there any solution thru i can manipulate my code with operating system and get notification thru mail or any other resource
We have critical windows services that must always be running at work and the way we handled this was to write a monitioring program that listens to communication from the critical services and sends out an email if any of them stop "calling in". Here are a few details (although a bit simplified):
1) We use MSMQ messages to have the computers running the services talk to the monitor. Each service writes to a specific queue and the monitor is set to read from those queues. Note that MSMQ has pros and cons--if you choose to use this method, be sure to read up on it a bit.
2) The critical programs write messages to the queue detailing what it is they are doing and if they have had any errors.
3) If it has been more than 20 seconds (adjust accordingly for your situation) and the services haven't had anything to do, they simply write a message to the queue saying that they haven't had anything to do for the last 20 seconds.
4) The monitor reads these messages, keeps track of how long it has been since it has heard from each queue and if any of them haven't sent at least an "I've been idle for 20 seconds" message within 30 seconds (note that this should be longer than the other time period), it sends an alert to our emails saying which service has been idle for too long. Similarly, if any service has had any critical errors, the monitor may report those right away, too.
ALTERNATELY
There are off-the-shelf programs you can buy to do some or all of this for you, but this solution has worked well for us. If you are interested in 3rd party tools, you may consider looking at Splunk, Big Brother, and Tripwire. I don't have much/any experience with these tools, so I'm not sure if they will do what you want or not.
You can make use of the OnStop() event in the ServiceBase as given here. Related discussion post is here

What's the easiest way to schedule a function to run at a specific time using C#

If I had a lot of messages in a database that I wanted to send, and each row specified a date and time to send the message, and a flag for if it has been sent.
These won't always be at fixed intervals, and more than 1 message may want to be sent at the same time.
In this case it would just queue them up and send in order of when they were created.
Is the easiest thing to do just to have a function that runs over and over again, once it completes it just runs again
So it would:
Start Running and check the current date/time
Check for any unsent messages
Send all the messages due to go out before and up to the time it started running
Start all over again and take the current date/time
My problem with this is, would it just be horribly inefficient to continuously have a method running, possibly for hours or days without actually sending a message.
The main strain in this case I think would be put on the database, it would constantly be getting hit with a query.
Is there a better way to schedule something like this to happen.
Or just do the above but every time it runs make it wait for 5 minutes before running again.
Does Workflow 4 offer anything suitable for scheduling perhaps?
You could always do a pre-emptive read of the next time value in the series and do a single sleep until then, instead of looping through short sleeps over and over.
Not sure if that's as elaborate as you want though
Maybe have a compiled view in the database which returns messages that are not sent (I assume there's a flag on each record?) and for which the intended send time is prior to the current time. Then a Windows Service or console application on a scheduled interval can hit that view (which can be performance-tuned in the database pretty well, I'd imagine) and send any messages returned by it.
You could use a windows service to accomplish this. Or if you're using MSSQL, you could even use a SQL Server Agent Job.
Several answers has suggested sending some messages then calling sleep until the next message is due to be sent.
How you sleep in this instance is all important.
You can - in theory - tell a thread to sleep for hours, however if during that time the app (or service) needs to shut down then you're in trouble. The process will be terminated, no cleanup will be executed. This is a less than ideal.
Don't get confused between the concept of polling for work to do, and sleeping between polls.
If you've to wait 5 minutes (or 5 hours) before next polling the database, that's fine, however you never want to *sleep for more than a second or two at a time.
What I'd do . . .
Write a windows service. The service has one active thread that polls the database, see's are any messages due to send, and sends them.
It will then poll on a configurable delay (1 minute, 5 minutes, 1 hour, what ever suits).
However it will never sleep for more than a second while it's waiting to poll the database.
If you can be assured that messages can only be added to send after the last message in the DB? If so you can check the time of the next message and not poll until that time.
However, if I find that the next message doesn't need to be sent for 5 hours, is it possible that while I'm waiting a message was added that should be sent in 30 minutes?
If so then you can never trust the "Next message time" and not poll until then, you have to continuously poll on your fixed interval NB worth saying again, your polling interval and your sleep interval are not the same thing.
How about writing a windows service which does this for you. This Windows service will run in the background and check the current time with your db records in a purticular interval (ex : every 5 minutes) and send emails to people and update corresponding records in your tables to set the Email Sent Flag to true
You can even have an SQL job which selects records which are not sent and matches wtih the current time and call a stored procedure which calls dot net assembly to send email . The dot net assembly can use SMTPClient to send emails.
It depends on what you use. Using a scheduled task or a service is perfectly acceptable for the scenario you describe.
You have to be careful though that you do not tie up resources if the process runs too often. It might be more efficient for it to run less often at peak times and more often during off-peak times.
Whatever method you prefer (make a Windows Service, use Task Scheduler, etc..), please bear in mind that your initial suggestion is exactly what is called busy waiting, which is something you should avoid unless you really know what you're doing.
What you describe isn't that bad if you extend it with
"when there are no messages due select the next time a message will be due and sleep till then".
Alternatively use a DB with "notification support" making the whole thing event-driven i.e. the DB sends you an event whenever a message is due.
you can use this one .NET Scheduled Timer for checking timeinervals and running the function(sending messages) at specific time intervals ....
I would say create a windows service with the timer. it may sleep for configured amount of seconds and then compare the datetime from the database. if it matched then send an e-mail & set the flag in the database for sent e-mails.
I recently implemented a windows service which utilized a class called IntervalHeap in the C5 collection class library. I then added a persistence layer which keeps tracks of the items and their intervals in case the service is stopped/crashed.
Has been in production for a few months and has been working very well.
We do this at a financial institution to send out internal e-mails from our intranet applications. Once every 15 minutes, a scheduling software (enterprise scheduler, not a Windows scheduled task) fires off a job. We have a view called PendingEmail on top of a table called EmailQueue that only lists out what needs to be sent this go around (the EmailQueue table has a PopDate, which is an effective date as to when the e-mail should get sent). The application fires off e-mails for whatever it found in the PendingEmails view.
The job sends out a maximum batch size of emails every 15 minutes, marking each record with whether it was successfully sent or whether there was an error (invalid email address, etc.) and what the Exception was, and whether we would like to try re-sending it the next time around. It updates that EmailQueue table all at once, not each record individually. The batch size was put in place to prevent the job from taking more than 15 minutes and stomping on itself.
I don't know that polling every so often is really consuming all that many resources, unless you're going to do it every 5 seconds or something. If you're sending out millions of messages you may need to distribute the work across multiple machines. If you're going to write some custom code, I would use a Timer over Thread.Sleep(), and set the Timer to tick every 5 minutes or whatever interval you'd like to perform work. An event fires on every tick that would subscribe to to start the routine that sends your messages.
See this post on Thread.Sleep() vs. the Timer class:
Compare using Thread.Sleep and Timer for delayed execution
Many databases allow events to be fired by triggers, eg. 'after insert'. The trigger is run by the database process/thread and the actions it can take are database-specific. It could, for instance, call a C or java procedure that signals a named semaphore upon which you emailer is waiting or exec. an emailer app directly. Look at 'trigger' or 'create trigger' for your database.

How to prevent my HTTP server from "sleeping"?

I've written a very basic HTTP-based server program that runs in the background on my computer to allow me to automate various tasks from my Android (via HTTP requests in Tasker). This all works fine (barring this problem), except that after more than about 30 minutes of inactivity, the application ends up falling asleep, as though it's being shunted out of memory, and takes a good minute or so to wake up when it receives an HTTP request or when I try to restore the window and interact with the UI.
I'm using System.Net.HttpListener to implement the server (using asynchronous calls to BeginListen). How should I go about keeping it on its toes?
Is it possible that your process memory is being swapped out to disk? Perhaps write a little monitor task that just pings it every 5 minutes? Note that this could also be useful for making sure it's still running - it could email you if it's down, for example :)
What is your OS (Windows XP / Seven / Server 2008 ...) and distribution ? (Home / Pro / SBS...) ?
Try to give hight priority to your process (like realtime).
You can also try to perform some task with your process every 10 minutes...
Maybe you could do another thread and check if your HttpListerner instance IsListening periodically?
Looks like the problem description is missing mentioning of the actual problem itself. On windows applications do not go into sleep mode. Inactive apps might be swapped, but it should not take very long time when it gets a request.
In .Net 2 I have noticed similar behavior due to garbage collection of the Listener Object itself or associated objects due to long inactivity. Try to keep a static reference of the listener object.This might help.

Categories