Creating a Windows Service with C#, continued - Installing the Service
(Page 4 of 4 )
Run the Visual Studio .NET Command Prompt and change directories to your TimeServerService project’s bin\Debug directory (or Release if you happened to build in Release mode). Type the following command:
installutil TimeService.exe
You should see a lot of stuff scroll by on the screen about the installation, and hopefully at the end you will see a message indicating that the service was successfully installed. Once the service is installed, go ahead and start it:
net start TimeServerService
You should see a message that the services are starting… and starting… and still starting. We forgot something! We need to fire off the Start() method in a separate thread so the OnStart() method doesn’t lead us into a nasty blocking loop. Add a reference to the System.Threading namespace at the top of your service class file, like this:
using System.Threading;
Change the OnStart() method to use a Thread rather than directly calling Start(), like so:
protected override void OnStart(string[] args)
{
this.isStopped = false;
Thread t = new Thread(new ThreadStart(this.Start));
t.Start();
}
Build the project. Before we can try to run the service again, we need to uninstall the old version by using this command:
installutil /u TimeService.exe
Once that’s done, install the service as we did before and start it with the net start command. Now set the test project as your startup project and run it. In the console output window you should see this message (hopefully with a different date and time, of course):
Sending request…
Received response: 1/21/2006 3:53:33 PM
Conclusion
We have now converted our little time application into a Windows Service! We created the service project, the service installer, and installed the service. Then we found out we had created an infinite loop in the service startup procedure so we moved the listener into its own thread to keep from blocking completion of the OnStart() method. We reinstalled the service, started it and tested it, with the desired results.
There are a few things left, though. We still need to start logging events and we still need to create a service controller form, and hopefully we will tuck it away in the system tray. We will cover those things in the final article of this series, coming soon!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |