This post was most recently updated on September 25th, 2014
What is a windows service?
A windows service is a process that runs in the background without user interface. Services are an ideal way to implement an application that runs constantly to perform a task.
Windows service application starts before the user logs into the computer. You cannot debug or run service. Instead you must install and start your service and then attach a debugger to the service.
How to create a windows service?
To create a Windows service, start Visual Studio, select the Visual C# project section and select Windows Service.
How to create an installer for a service?
In design view of service. Right click the designer and then Add installer.
Set the StartType property for the ProjectInstaller component. 1. Automatic 2. Manual 3. Disabled
Set the
1 |
Description |
and
1 |
DisplayName |
properties for the ServiceInstaller component. Now right click on serviceProcessInstaller component and specify the
1 |
Account |
property to
1 |
LocalSystem |
How to implement a service?
Now its time to write code to implement the service. To jump into the code Right click on the service designer and choose ViewCode option. The OnStart event code executes when a service starts and OnStop event code executes when the service stops. Add your code on start method and also stop as you need.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { //do somthing } protected override void OnStop() { //do somthing } } |
Now build the project an install the service
How to install a service?
After building the service, install the service manually using Visual Studio Command Prompt. Open Visual Studio Command Prompt from visual studio tools.
Syntex:
installutil.exe < path to executable >
Example:
For install Service
installutil.exe D:\WebService\bin\Release\WindowsService.exe
For Uninstall Service
installutil.exe /u D:\WebService\bin\Release\WindowsService.exe
After successful installation of windows service, open services from Control Panel–>System and Security–>Administrative Tools–>Services. In the right pane, right click your service and then click start.
You can stop, pause, resume or restart the service. You can also control services from the command line by using the Net command with the format
1 |
Net Start |
or
1 |
Net Stop |
.