Simplest Service

Windows service is somewhat considered relic of the past. It is just not sexy enough for users. More often than not I see business applications that need to be always on sitting in tray processing their data. And there is mandatory "do not log off" paper sitting on keyboard.

And I always hear same excuses. My version of Visual Studio does not support it (from Express clan); It is very hard to debug it; It is confusing; etc. Worst thing is that Windows services made is C# is neither hard to create nor it is (too) hard to debug. You just need to do things your way.

First thing to keep in mind is that service is just simple Windows Form application. There is no reason why you need to debug it any differently. Just go into properties and set Program.cs (or App.cs, as I like to name it) to be startup object. When code starts running, just check for command line parameter (I like to use /Interactive). If that parameter is present DO NOT use ServiceBase.Run but start background thread manually.

Other annoying thing about services is installing them via installutil. You do not need to do that either. For install just execute:

ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });

For uninstall it is:

ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });

Of course, that can be done with /Install and /Uninstall parameters on command line.

As far as threading goes there is no escape. You must have your code in different thread in order to run a service. Windows Service Manager will call your OnStart and OnStop methods but it will not wait forever for result. My preferred method is just creating static class with methods Start, Stop and Run. Start gets called from OnStart and it starts a thread that executes private Run method (new Thread(Run)). Stop method gets called from OnStop to kill the party. Yes, there is some signaling needed for properly canceling everything but there is not much more to it.

Jut check sample application and happy background grinding.

One thought to “Simplest Service”

Leave a Reply

Your email address will not be published. Required fields are marked *