I am getting into windows services and looking over some tutorials, but they are all very dumbed down. They usually involve printing something out in the overridden OnStart method. That sounds like it gets called once. Now where would I put code that needs to be run continuously?
To debug without installing, add the code as follow, mainly #if (! DEBUG). You will be able to step through the code when you run the Windows Service without installing.
All of the On... methods in your service class should return as quickly as possible. They will end up being called whenever the Windows service controller interacts with your service, and the service controller will be waiting for a successful return. Whenever you use the Services Control Panel applet and you start or stop a service, that progress bar you see is what is shown while waiting for that service's equivalent of OnStart or OnStop to return.
So the typical thing to do in OnStart is one or more of the following:
System.Threading.Timer
variety) that will periodically perform whatever action your service does periodically (perhaps polling for some state)In any of these cases, your service's task is performed asynchronously, and you exit from OnStart immediately. But remember to keep track of your thread, timer, TcpListener, or whatever, so that you can interact with it in OnStop (and optionally OnPause and OnContinue). Usually the thing to do is to dispose of any timers (so they won't fire any more), shut down any sockets or listeners, then set a ManualResetEvent. Any threads you have running should check this event periodically and exit once it's signaled. If you want to ensure a successful shutdown of the service and risk possible data loss, you might join to any running threads with a reasonable timeout (30 seconds is common), then abort any threads that are still running after the timeout has expired.
The same as any other project that has more than a couple of classes - you put it in a separate project.
The 'Windows Service' project should just contain the boilerplate stuff to start the service, any timers that are part of the service, and that sort of thing. Putting the rest in another project allows you to use your business logic in a desktop app, a web app, as a WCF service and so on later on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With