Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I put the bulk of my code when writing a windows service?

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?

like image 307
Matt Vaughan Avatar asked Aug 17 '12 03:08

Matt Vaughan


People also ask

How do I debug a Windows service without installing?

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.


2 Answers

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:

  • start a separate thread that performs the constant task your service will perform
  • set up a timer (of the System.Threading.Timer variety) that will periodically perform whatever action your service does periodically (perhaps polling for some state)
  • start listening asynchronously on a network port, perhaps with a TcpListener or UdpClient
  • subscribe to some system event

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.

like image 122
P Daddy Avatar answered Oct 14 '22 09:10

P Daddy


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.

like image 26
Kirk Broadhurst Avatar answered Oct 14 '22 10:10

Kirk Broadhurst