Windows Service Applications
Windows Service Applications
Windows Service Applications
WARNING
This documentation isn't for the latest version of Windows Service. For the latest content on Windows Services using
BackgroundService and the Worker Service template, see:
Worker Services in .NET
Create a Windows Service using BackgroundService
Using Visual Studio or the .NET Framework SDK, you can easily create services by creating an application that is
installed as a service. This type of application is called a Windows service. With framework features, you can
create services, install them, and start, stop, and otherwise control their behavior.
NOTE
In Visual Studio you can create a service in managed code in Visual C# or Visual Basic, which can interoperate with
existing C++ code if required. Or, you can create a Windows service in native C++ by using the ATL Project Wizard.
In this section
Introduction to Windows Service Applications
Provides an overview of Windows service applications, the lifetime of a service, and how service applications
differ from other common project types.
Walkthrough: Creating a Windows Service Application in the Component Designer
Provides an example of creating a service in Visual Basic and Visual C#.
Service Application Programming Architecture
Explains the language elements used in service programming.
How to: Create Windows Services
Describes the process of creating and configuring Windows services using the Windows service project
template.
Related sections
ServiceBase - Describes the major features of the ServiceBase class, which is used to create services.
ServiceProcessInstaller - Describes the features of the ServiceProcessInstaller class, which is used along with the
ServiceInstaller class to install and uninstall your services.
ServiceInstaller - Describes the features of the ServiceInstaller class, which is used along with the
ServiceProcessInstaller class to install and uninstall your service.
Create Projects from Templates - Describes the projects types used in this chapter and how to choose between
them.
Introduction to Windows Service Applications
10/18/2022 • 6 minutes to read • Edit Online
WARNING
This documentation isn't for the latest version of Windows Service. For the latest content on Windows Services using
BackgroundService and the Worker Service template, see:
Worker Services in .NET
Create a Windows Service using BackgroundService
Microsoft Windows services, formerly known as NT services, enable you to create long-running executable
applications that run in their own Windows sessions. These services can be automatically started when the
computer boots, can be paused and restarted, and do not show any user interface. These features make services
ideal for use on a server or whenever you need long-running functionality that does not interfere with other
users who are working on the same computer. You can also run services in the security context of a specific user
account that is different from the logged-on user or the default computer account. For more information about
services and Windows sessions, see the Windows SDK documentation.
You can easily create services by creating an application that is installed as a service. For example, suppose you
want to monitor performance counter data and react to threshold values. You could write a Windows Service
application that listens to the performance counter data, deploy the application, and begin collecting and
analyzing data.
You create your service as a Microsoft Visual Studio project, defining code within it that controls what
commands can be sent to the service and what actions should be taken when those commands are received.
Commands that can be sent to a service include starting, pausing, resuming, and stopping the service; you can
also execute custom commands.
After you create and build the application, you can install it by running the command-line utility InstallUtil.exe
and passing the path to the service's executable file. You can then use the Ser vices Control Manager to start,
stop, pause, resume, and configure your service. You can also accomplish many of these same tasks in the
Ser vices node in Ser ver Explorer or by using the ServiceController class.
Service Lifetime
A service goes through several internal states in its lifetime. First, the service is installed onto the system on
which it will run. This process executes the installers for the service project and loads the service into the
Ser vices Control Manager for that computer. The Ser vices Control Manager is the central utility provided
by Windows to administer services.
After the service has been loaded, it must be started. Starting the service allows it to begin functioning. You can
start a service from the Ser vices Control Manager , from Ser ver Explorer , or from code by calling the Start
method. The Start method passes processing to the application's OnStart method and processes any code you
have defined there.
A running service can exist in this state indefinitely until it is either stopped or paused or until the computer
shuts down. A service can exist in one of three basic states: Running, Paused, or Stopped. The service can also
report the state of a pending command: ContinuePending, PausePending, StartPending, or StopPending. These
statuses indicate that a command has been issued, such as a command to pause a running service, but has not
been carried out yet. You can query the Status to determine what state a service is in, or use the WaitForStatus to
carry out an action when any of these states occurs.
You can pause, stop, or resume a service from the Ser vices Control Manager , from Ser ver Explorer , or by
calling methods in code. Each of these actions can call an associated procedure in the service (OnStop, OnPause,
or OnContinue), in which you can define additional processing to be performed when the service changes state.
Types of Services
There are two types of services you can create in Visual Studio using the .NET Framework. Services that are the
only service in a process are assigned the type Win32OwnProcess. Services that share a process with another
service are assigned the type Win32ShareProcess. You can retrieve the service type by querying the ServiceType
property.
You might occasionally see other service types if you query existing services that were not created in Visual
Studio. For more information on these, see the ServiceType.
Requirements
Services must be created in a Windows Ser vice application project or another .NET Framework–
enabled project that creates an .exe file when built and inherits from the ServiceBase class.
Projects containing Windows services must have installation components for the project and its services.
This can be easily accomplished from the Proper ties window. For more information, see How to: Add
Installers to Your Service Application.
See also
Windows Service Applications
Service Application Programming Architecture
How to: Create Windows Services
How to: Install and Uninstall Services
How to: Start Services
How to: Debug Windows Service Applications
Walkthrough: Creating a Windows Service Application in the Component Designer
How to: Add Installers to Your Service Application
Tutorial: Create a Windows service app
10/18/2022 • 15 minutes to read • Edit Online
WARNING
This documentation isn't for the latest version of Windows Service. For the latest content on Windows Services using
BackgroundService and the Worker Service template, see:
Worker Services in .NET
Create a Windows Service using BackgroundService
This article demonstrates how to create a Windows service app in Visual Studio that writes messages to an
event log.
Create a service
To begin, create the project and set the values that are required for the service to function correctly.
1. From the Visual Studio File menu, select New > Project (or press Ctrl+Shift+N) to open the New
Project window.
2. Find and select the Windows Ser vice (.NET Framework) project template.
NOTE
If you don't see the Windows Ser vice template, you may need to install the .NET desktop development
workload using Visual Studio Installer.
' To access the constructor in Visual Basic, select New from the
' method name drop-down list.
Public Sub New()
MyBase.New()
InitializeComponent()
Me.EventLog1 = New System.Diagnostics.EventLog
If Not System.Diagnostics.EventLog.SourceExists("MySource") Then
System.Diagnostics.EventLog.CreateEventSource("MySource",
"MyNewLog")
End If
EventLog1.Source = "MySource"
EventLog1.Log = "MyNewLog"
End Sub
5. Add a using statement to MyNewSer vice.cs (if it doesn't already exist), or an Imports statement to
MyNewSer vice.vb , for the System.Diagnostics namespace:
using System.Diagnostics;
Imports System.Diagnostics
' To access the OnStart in Visual Basic, select OnStart from the
' method name drop-down list.
Protected Overrides Sub OnStart(ByVal args() As String)
EventLog1.WriteEntry("In OnStart")
End Sub
Polling
Because a service application is designed to be long-running, it usually polls or monitors the system, which you
set up in the OnStart method. The OnStart method must return to the operating system after the service's
operation has begun so that the system isn't blocked.
To set up a simple polling mechanism, use the System.Timers.Timer component. The timer raises an Elapsed
event at regular intervals, at which time your service can do its monitoring. You use the Timer component as
follows:
Set the properties of the Timer component in the MyNewService.OnStart method.
Start the timer by calling the Start method.
Se t u p t h e p o l l i n g m e c h a n i sm
1. Add a using statement to MyNewSer vice.cs , or an Imports statement to MyNewSer vice.vb , for the
System.Timers namespace:
using System.Timers;
Imports System.Timers
2. Add the following code in the MyNewService.OnStart event to set up the polling mechanism:
3. In the MyNewService class, add a member variable. It contains the identifier of the next event to write into
the event log:
4. In the MyNewService class, add the OnTimer method to handle the Timer.Elapsed event:
using System.Runtime.InteropServices;
Imports System.Runtime.InteropServices
2. Add the following code to MyNewSer vice.cs , or MyNewSer vice.vb , to declare the ServiceState
values and to add a structure for the status, which you'll use in a platform invoke call:
public enum ServiceState
{
SERVICE_STOPPED = 0x00000001,
SERVICE_START_PENDING = 0x00000002,
SERVICE_STOP_PENDING = 0x00000003,
SERVICE_RUNNING = 0x00000004,
SERVICE_CONTINUE_PENDING = 0x00000005,
SERVICE_PAUSE_PENDING = 0x00000006,
SERVICE_PAUSED = 0x00000007,
}
[StructLayout(LayoutKind.Sequential)]
public struct ServiceStatus
{
public int dwServiceType;
public ServiceState dwCurrentState;
public int dwControlsAccepted;
public int dwWin32ExitCode;
public int dwServiceSpecificExitCode;
public int dwCheckPoint;
public int dwWaitHint;
};
<StructLayout(LayoutKind.Sequential)>
Public Structure ServiceStatus
Public dwServiceType As Long
Public dwCurrentState As ServiceState
Public dwControlsAccepted As Long
Public dwWin32ExitCode As Long
Public dwServiceSpecificExitCode As Long
Public dwCheckPoint As Long
Public dwWaitHint As Long
End Structure
NOTE
The Service Control Manager uses the dwWaitHint and dwCheckpoint members of the SERVICE_STATUS
structure to determine how much time to wait for a Windows service to start or shut down. If your OnStart and
OnStop methods run long, your service can request more time by calling SetServiceStatus again with an
incremented dwCheckPoint value.
3. In the MyNewService class, declare the SetServiceStatus function by using platform invoke:
Declare Auto Function SetServiceStatus Lib "advapi32.dll" (ByVal handle As IntPtr, ByRef
serviceStatus As ServiceStatus) As Boolean
4. To implement the SERVICE_START_PENDING status, add the following code to the beginning of the
OnStart method:
5. Add code to the end of the OnStart method to set the status to SERVICE_RUNNING:
6. (Optional) If OnStop is a long-running method, repeat this procedure in the OnStop method. Implement
the SERVICE_STOP_PENDING status and return the SERVICE_STOPPED status before the OnStop method
exits.
For example:
6. Add text to the DisplayName property. For example, MyNewService Display Name.
This text appears in the Display Name column of the Ser vices window. This name can be different from
the ServiceName property, which is the name the system uses (for example, the name you use for the
net start command to start your service).
9. In the Design view for ProjectInstaller , choose ser viceProcessInstaller1 for a Visual C# project, or
Ser viceProcessInstaller1 for a Visual Basic project, then choose Proper ties from the shortcut menu.
Set the Account property to LocalSystem from the drop-down list.
This setting installs the service and runs it by using the local system account.
IMPORTANT
The LocalSystem account has broad permissions, including the ability to write to the event log. Use this account
with caution, because it might increase your risk of attacks from malicious software. For other tasks, consider
using the LocalService account, which acts as a non-privileged user on the local computer and presents
anonymous credentials to any remote server. This example fails if you try to use the LocalService account, because
it needs permission to write to the event log.
For more information about installers, see How to: Add installers to your service application.
A Windows service can accept command-line arguments, or startup parameters. When you add code to process
startup parameters, a user can start your service with their own custom startup parameters in the service
properties window. However, these startup parameters aren't persisted the next time the service starts. To set
startup parameters permanently, set them in the registry.
Each Windows service has a registry entry under the
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Ser vices subkey. Under each service's subkey, use
the Parameters subkey to store information that your service can access. You can use application configuration
files for a Windows service the same way you do for other types of programs. For sample code, see
ConfigurationManager.AppSettings.
To add startup parameters
1. Select Program.cs , or MyNewSer vice.Designer.vb , then choose View Code from the shortcut menu.
In the Main method, change the code to add an input parameter and pass it to the service constructor:
2. In MyNewSer vice.cs , or MyNewSer vice.vb , change the MyNewService constructor to process the input
parameter as follows:
using System.Diagnostics;
if (args.Length > 0)
{
eventSourceName = args[0];
}
if (args.Length > 1)
{
logName = args[1];
}
if (!EventLog.SourceExists(eventSourceName))
{
EventLog.CreateEventSource(eventSourceName, logName);
}
eventLog1.Source = eventSourceName;
eventLog1.Log = logName;
}
Imports System.Diagnostics
This code sets the event source and log name according to the startup parameters that the user supplies.
If no arguments are supplied, it uses default values.
3. To specify the command-line arguments, add the following code to the ProjectInstaller class in
ProjectInstaller.cs , or ProjectInstaller.vb :
protected override void OnBeforeInstall(IDictionary savedState)
{
string parameter = "MySource1\" \"MyLogFile1";
Context.Parameters["assemblypath"] = "\"" + Context.Parameters["assemblypath"] + "\" \"" +
parameter + "\"";
base.OnBeforeInstall(savedState);
}
Typically, this value contains the full path to the executable for the Windows service. For the service to
start up correctly, the user must supply quotation marks for the path and each individual parameter. A
user can change the parameters in the ImagePath registry entry to change the startup parameters for
the Windows service. However, a better way is to change the value programmatically and expose the
functionality in a user-friendly way, such as by using a management or configuration utility.
installutil MyNewService.exe
2. To start the service, choose Star t from the service's shortcut menu.
3. To stop the service, choose Stop from the service's shortcut menu.
4. (Optional) From the command line, use the commands net star t <ser vice name> and net stop
<ser vice name> to start and stop your service.
Verify the event log output of your service
1. In Windows, open the Event Viewer desktop app. Enter Event Viewer in the Windows search bar, and
then select Event Viewer from the search results.
TIP
In Visual Studio, you can access event logs by opening Ser ver Explorer from the View menu (or press
Ctrl+Alt+S) and expanding the Event Logs node for the local computer.
installutil.exe /u MyNewService.exe
If the service uninstalls successfully, the command reports that your service was successfully removed.
For more information, see How to: Install and uninstall services.
Next steps
Now that you've created the service, you can:
Create a standalone setup program for others to use to install your Windows service. Use the WiX Toolset
to create an installer for a Windows service. For other ideas, see Create an installer package.
Explore the ServiceController component, which enables you to send commands to the service you've
installed.
Instead of creating the event log when the application runs, use an installer to create an event log when
you install the application. The event log is deleted by the installer when you uninstall the application. For
more information, see EventLogInstaller.
See also
Windows service applications
Introduction to Windows service applications
How to: Debug Windows service applications
Services (Windows)
Service Application Programming Architecture
10/18/2022 • 3 minutes to read • Edit Online
WARNING
This documentation isn't for the latest version of Windows Service. For the latest content on Windows Services using
BackgroundService and the Worker Service template, see:
Worker Services in .NET
Create a Windows Service using BackgroundService
Windows Service applications are based on a class that inherits from the System.ServiceProcess.ServiceBase
class. You override methods from this class and define functionality for them to determine how your service
behaves.
The main classes involved in service creation are:
System.ServiceProcess.ServiceBase — You override methods from the ServiceBase class when creating a
service and define the code to determine how your service functions in this inherited class.
System.ServiceProcess.ServiceProcessInstaller and System.ServiceProcess.ServiceInstaller —You use
these classes to install and uninstall your service.
In addition, a class named ServiceController can be used to manipulate the service itself. This class is not
involved in the creation of a service, but can be used to start and stop the service, pass commands to it, and
return a series of enumerations.
M ET H O D O VERRIDE TO
NOTE
These methods represent states that the service moves through in its lifetime; the service transitions from one state to
the next. For example, you will never get the service to respond to an OnContinue command before OnStart has been
called.
There are several other properties and methods that are of interest. These include:
The Run method on the ServiceBase class. This is the main entry point for the service. When you create a
service using the Windows Service template, code is inserted in your application's Main method to run
the service. This code looks like this:
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[]
{ new Service1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
NOTE
These examples use an array of type ServiceBase, into which each service your application contains can be added,
and then all of the services can be run together. If you are only creating a single service, however, you might
choose not to use the array and simply declare a new object inheriting from ServiceBase and then run it. For an
example, see How to: Write Services Programmatically.
A series of properties on the ServiceBase class. These determine what methods can be called on your
service. For example, when the CanStop property is set to true , the OnStop method on your service can
be called. When the CanPauseAndContinue property is set to true , the OnPause and OnContinue
methods can be called. When you set one of these properties to true , you should then override and
define processing for the associated methods.
NOTE
Your service must override at least OnStart and OnStop to be useful.
You can also use a component called the ServiceController to communicate with and control the behavior of an
existing service.
See also
Introduction to Windows Service Applications
How to: Create Windows Services
How to: Create Windows Services
10/18/2022 • 2 minutes to read • Edit Online
WARNING
This documentation isn't for the latest version of Windows Service. For the latest content on Windows Services using
BackgroundService and the Worker Service template, see:
Worker Services in .NET
Create a Windows Service using BackgroundService
When you create a service, you can use a Visual Studio project template called Windows Ser vice . This
template automatically does much of the work for you by referencing the appropriate classes and namespaces,
setting up the inheritance from the base class for services, and overriding several of the methods you're likely to
want to override.
WARNING
The Windows Services project template is not available in the Express edition of Visual Studio.
NOTE
For instructions on writing a service without using the template, see How to: Write Services Programmatically.
2. In the Proper ties window, set the ServiceName property for your service.
NOTE
The value of the ServiceName property must always match the name recorded in the installer classes. If you
change this property, you must update the ServiceName property of installer classes as well.
3. Set any of the following properties to determine how your service will function.
P RO P ERT Y SET T IN G
NOTE
When CanStop or CanPauseAndContinue are set to false , the Ser vice Control Manager will disable the
corresponding menu options to stop, pause, or continue the service.
4. Access the Code Editor and fill in the processing you want for the OnStart and OnStop procedures.
5. Override any other methods for which you want to define functionality.
6. Add the necessary installers for your service application. For more information, see How to: Add Installers
to Your Service Application.
7. Build your project by selecting Build Solution from the Build menu.
NOTE
Do not press F5 to run your project — you cannot run a service project in this way.
8. Install the service. For more information, see How to: Install and Uninstall Services.
See also
Introduction to Windows Service Applications
How to: Write Services Programmatically
How to: Add Installers to Your Service Application
How to: Log Information About Services
How to: Start Services
How to: Specify the Security Context for Services
How to: Install and Uninstall Services
Walkthrough: Creating a Windows Service Application in the Component Designer
How to: Write Services Programmatically
10/18/2022 • 2 minutes to read • Edit Online
WARNING
This documentation isn't for the latest version of Windows Service. For the latest content on Windows Services using
BackgroundService and the Worker Service template, see:
Worker Services in .NET
Create a Windows Service using BackgroundService
If you choose not to use the Windows Service project template, you can write your own services by setting up
the inheritance and other infrastructure elements yourself. When you create a service programmatically, you
must perform several steps that the template would otherwise handle for you:
You must set up your service class to inherit from the ServiceBase class.
You must create a Main method for your service project that defines the services to run and calls the Run
method on them.
You must override the OnStart and OnStop procedures and fill in any code you want them to run.
To write a service programmatically
1. Create an empty project and create a reference to the necessary namespaces by following these steps:
a. In Solution Explorer , right-click the References node and click Add Reference .
b. On the .NET Framework tab, scroll to System.dll and click Select .
c. Scroll to System.Ser viceProcess.dll and click Select .
d. Click OK .
2. Add a class and configure it to inherit from ServiceBase:
public UserService1()
{
this.ServiceName = "MyService2";
this.CanStop = true;
this.CanPauseAndContinue = true;
this.AutoLog = true;
}
Public Sub New()
Me.ServiceName = "MyService2"
Me.CanStop = True
Me.CanPauseAndContinue = True
Me.AutoLog = True
End Sub
4. Create a Main method for your class, and use it to define the service your class will contain;
userService1 is the name of the class:
5. Override the OnStart method, and define any processing you want to occur when your service is started.
6. Override any other methods you want to define custom processing for, and write code to determine the
actions the service should take in each case.
7. Add the necessary installers for your service application. For more information, see How to: Add Installers
to Your Service Application.
8. Build your project by selecting Build Solution from the Build menu.
NOTE
Do not press F5 to run your project — you cannot run a service project in this way.
9. Create a setup project and the custom actions to install your service. For an example, see Walkthrough:
Creating a Windows Service Application in the Component Designer.
10. Install the service. For more information, see How to: Install and Uninstall Services.
See also
Introduction to Windows Service Applications
How to: Create Windows Services
How to: Add Installers to Your Service Application
How to: Log Information About Services
Walkthrough: Creating a Windows Service Application in the Component Designer
How to: Add Installers to Your Service Application
10/18/2022 • 2 minutes to read • Edit Online
WARNING
This documentation isn't for the latest version of Windows Service. For the latest content on Windows Services using
BackgroundService and the Worker Service template, see:
Worker Services in .NET
Create a Windows Service using BackgroundService
Visual Studio ships installation components that can install resources associated with your service applications.
Installation components register an individual service on the system to which it is being installed and let the
Services Control Manager know that the service exists. When you work with a service application, you can select
a link in the Properties window to automatically add the appropriate installers to your project.
NOTE
Property values for your service are copied from the service class to the installer class. If you update the property values
on the service class, they are not automatically updated in the installer.
When you add an installer to your project, a new class (which, by default, is named ProjectInstaller ) is created
in the project, and instances of the appropriate installation components are created within it. This class acts as a
central point for all of the installation components your project needs. For example, if you add a second service
to your application and click the Add Installer link, a second installer class is not created; instead, the necessary
additional installation component for the second service is added to the existing class.
You do not need to do any special coding within the installers to make your services install correctly. However,
you may occasionally need to modify the contents of the installers if you need to add special functionality to the
installation process.
NOTE
The dialog boxes and menu commands you see might differ from those described in Help depending on your active
settings or edition. To change your settings, choose Impor t and Expor t Settings on the Tools menu. For more
information, see Personalize the Visual Studio IDE.
VA L UE RESULT
6. To determine the security context in which your service will run, click the ServiceProcessInstaller
component and set the appropriate property values. For more information, see How to: Specify the
Security Context for Services.
7. Override any methods for which you need to perform custom processing.
8. Perform steps 1 through 7 for each additional service in your project.
NOTE
For each additional service in your project, you must add an additional ServiceInstaller component to the project's
ProjectInstaller class. The ServiceProcessInstaller component added in step three works with all of the
individual service installers in the project.
See also
Introduction to Windows Service Applications
How to: Install and Uninstall Services
How to: Start Services
How to: Specify the Security Context for Services
How to: Specify the Security Context for Services
10/18/2022 • 2 minutes to read • Edit Online
WARNING
This documentation isn't for the latest version of Windows Service. For the latest content on Windows Services using
BackgroundService and the Worker Service template, see:
Worker Services in .NET
Create a Windows Service using BackgroundService
By default, services run in a different security context than that of the logged-in user. Services run in the context
of the default system account, called LocalSystem , which gives them different access privileges to system
resources than the user. You can change this behavior to specify a different user account under which your
service should run.
You set the security context by manipulating the Account property for the process within which the service runs.
This property allows you to set the service to one of four account types:
User , which causes the system to prompt for a valid user name and password when the service is
installed and runs in the context of an account specified by a single user on the network;
LocalService, which runs in the context of an account that acts as a non-privileged user on the local
computer, and presents anonymous credentials to any remote server;
LocalSystem , which runs in the context of an account that provides extensive local privileges, and
presents the computer's credentials to any remote server;
NetworkService, which runs in the context of an account that acts as a non-privileged user on the local
computer, and presents the computer's credentials to any remote server.
For more information, see the ServiceAccount enumeration.
To specify the security context for a service
1. After creating your service, add the necessary installers for it. For more information, see How to: Add
Installers to Your Service Application.
2. In the designer, access the ProjectInstaller class and click the service process installer for the service
you are working with.
NOTE
For every service application, there are at least two installation components in the ProjectInstaller class —
one that installs the processes for all services in the project, and one installer for each service the application
contains. In this instance, you want to select ServiceProcessInstaller.
3. In the Proper ties window, set the Account to the appropriate value.
See also
Introduction to Windows Service Applications
How to: Add Installers to Your Service Application
How to: Create Windows Services
How to: Install and uninstall Windows services
10/18/2022 • 3 minutes to read • Edit Online
WARNING
This documentation isn't for the latest version of Windows Service. For the latest content on Windows Services using
BackgroundService and the Worker Service template, see:
Worker Services in .NET
Create a Windows Service using BackgroundService
If you're developing a Windows service with .NET Framework, you can quickly install your service app by using
the InstallUtil.exe command-line utility or PowerShell. Developers who want to release a Windows service that
users can install and uninstall can use the free WiX Toolset or commercial tools like Advanced Installer,
InstallShield, and others. For more information, see Create an installer package (Windows desktop).
WARNING
If you want to uninstall a service from your computer, don't follow the steps in this article. Instead, find out which
program or software package installed the service, and then choose Apps in Settings to uninstall that program. Many
services are integral parts of Windows; if you remove them, you might cause system instability.
To use the steps in this article, you first need to add a service installer to your Windows service. For more
information, see Walkthrough: Creating a Windows service app.
You can't run Windows service projects directly from the Visual Studio development environment by pressing
F5. Before you can run the project, you must install the service in the project.
TIP
You can use Ser ver Explorer to verify that you've installed or uninstalled your service.
installutil <yourproject>.exe
If you're using the Developer Command Prompt for Visual Studio, InstallUtil.exe is already on the system
path. Otherwise, you can add it to the path, or use the fully qualified path to invoke it. This tool is installed
with the .NET Framework in %WINDIR%\Microsoft.NET\Framework[64]\<framework_version>.
For example:
For the 32-bit version of the .NET Framework 4 or 4.5 and later, if your Windows installation directory
is C:\Windows, the default path is C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe.
For the 64-bit version of the .NET Framework 4 or 4.5 and later, the default path is
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe.
installutil /u <yourproject>.exe
3. After the executable for a service is deleted, the service might still be present in the registry. If that's the
case, use the command sc delete to remove the entry for the service from the registry.
NOTE
You must have PowerShell 6 or later to use this cmdlet. For information about updating PowerShell, see Installing
PowerShell on Windows.
3. After the executable for a service is deleted, the service might still be present in the registry. If that's the
case, use the command sc delete to remove the entry for the service from the registry.
See also
Introduction to Windows service applications
How to: Create Windows services
How to: Add installers to your service application
Installutil.exe (Installer tool)
How to: Start Services
10/18/2022 • 2 minutes to read • Edit Online
WARNING
This documentation isn't for the latest version of Windows Service. For the latest content on Windows Services using
BackgroundService and the Worker Service template, see:
Worker Services in .NET
Create a Windows Service using BackgroundService
After a service is installed, it must be started. Starting calls the OnStart method on the service class. Usually, the
OnStart method defines the useful work the service will perform. After a service starts, it remains active until it
is manually paused or stopped.
Services can be set up to start automatically or manually. A service that starts automatically will be started when
the computer on which it is installed is rebooted or first turned on. A user must start a service that starts
manually.
NOTE
By default, services created with Visual Studio are set to start manually.
There are several ways you can manually start a service — from Ser ver Explorer , from the Ser vices Control
Manager , or from code using a component called the ServiceController.
You set the StartType property on the ServiceInstaller class to determine whether a service should be started
manually or automatically.
TIP
To prevent your service from being started at all, you can set the StartType property to Disabled . You might do
this if you are going to reboot a server several times and want to save time by preventing the services that would
normally start from starting up.
NOTE
These and other properties can be changed after your service is installed.
There are several ways you can start a service that has its StartType process set to Manual — from
Ser ver Explorer , from the Windows Ser vices Control Manager , or from code. It is important to
note that not all of these methods actually start the service in the context of the Ser vices Control
Manager ; Ser ver Explorer and programmatic methods of starting the service actually manipulate the
controller.
See also
Introduction to Windows Service Applications
How to: Create Windows Services
How to: Add Installers to Your Service Application
How to: Pause a Windows Service (Visual Basic)
10/18/2022 • 2 minutes to read • Edit Online
WARNING
This documentation isn't for the latest version of Windows Service. For the latest content on Windows Services using
BackgroundService and the Worker Service template, see:
Worker Services in .NET
Create a Windows Service using BackgroundService
This example uses the ServiceController component to pause the IIS Admin service on the local computer.
Example
Dim theController As System.ServiceProcess.ServiceController
theController = New System.ServiceProcess.ServiceController("IISAdmin")
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in
Windows Operating System > Windows Ser vices . For more information, see Code Snippets.
Robust Programming
The MachineName property of the ServiceController class is the local computer by default. To reference
Windows services on another computer, change the MachineName property to the name of that computer.
The following conditions may cause an exception:
The service cannot be paused. (InvalidOperationException)
An error occurred when accessing a system API. (Win32Exception)
See also
ServiceController
ServiceControllerStatus
WaitForStatus
How to: Continue a Windows Service (Visual Basic)
How to: Continue a Windows Service (Visual Basic)
10/18/2022 • 2 minutes to read • Edit Online
WARNING
This documentation isn't for the latest version of Windows Service. For the latest content on Windows Services using
BackgroundService and the Worker Service template, see:
Worker Services in .NET
Create a Windows Service using BackgroundService
This example uses the ServiceController component to continue the IIS Admin service on the local computer.
Example
Dim theController As System.ServiceProcess.ServiceController
theController = New System.ServiceProcess.ServiceController("IISAdmin")
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in
Windows Operating System > Windows Ser vices . For more information, see Code Snippets.
Robust Programming
The MachineName property of the ServiceController class is the local computer by default. To reference
Windows services on another computer, change the MachineName property to the name of that computer.
You cannot call the Continue method on a service until the service controller status is Paused.
The following conditions may cause an exception:
The service cannot be resumed. (InvalidOperationException)
An error occurred when accessing a system API. (Win32Exception)
.NET Framework Security
Control of services on the computer may be restricted by using the ServiceControllerPermissionAccess
enumeration to set permissions in the ServiceControllerPermission class.
Access to service information may be restricted by using the PermissionState enumeration to set permissions in
the SecurityPermission class.
See also
ServiceController
ServiceControllerStatus
How to: Pause a Windows Service (Visual Basic)
How to: Debug Windows Service Applications
10/18/2022 • 5 minutes to read • Edit Online
WARNING
This documentation isn't for the latest version of Windows Service. For the latest content on Windows Services using
BackgroundService and the Worker Service template, see:
Worker Services in .NET
Create a Windows Service using BackgroundService
A service must be run from within the context of the Services Control Manager rather than from within Visual
Studio. For this reason, debugging a service is not as straightforward as debugging other Visual Studio
application types. To debug a service, you must start the service and then attach a debugger to the process in
which it is running. You can then debug your application by using all of the standard debugging functionality of
Visual Studio.
Cau t i on
You should not attach to a process unless you know what the process is and understand the consequences of
attaching to and possibly killing that process. For example, if you attach to the WinLogon process and then stop
debugging, the system will halt because it can't operate without WinLogon.
You can attach the debugger only to a running service. The attachment process interrupts the current
functioning of your service; it doesn't actually stop or pause the service's processing. That is, if your service is
running when you begin debugging, it is still technically in the Started state as you debug it, but its processing
has been suspended.
After attaching to the process, you can set breakpoints and use these to debug your code. Once you exit the
dialog box you use to attach to the process, you are effectively in debug mode. You can use the Services Control
Manager to start, stop, pause and continue your service, thus hitting the breakpoints you've set. You can later
remove this dummy service after debugging is successful.
This article covers debugging a service that's running on the local computer, but you can also debug Windows
Services that are running on a remote computer. See Remote Debugging.
NOTE
Debugging the OnStart method can be difficult because the Services Control Manager imposes a 30-second limit on all
attempts to start a service. For more information, see Troubleshooting: Debugging Windows Services.
WARNING
To get meaningful information for debugging, the Visual Studio debugger needs to find symbol files for the binaries that
are being debugged. If you are debugging a service that you built in Visual Studio, the symbol files (.pdb files) are in the
same folder as the executable or library, and the debugger loads them automatically. If you are debugging a service that
you didn't build, you should first find symbols for the service and make sure they can be found by the debugger. See
Specify Symbol (.pdb) and Source Files in the Visual Studio Debugger. If you're debugging a system process or want to
have symbols for system calls in your services, you should add the Microsoft Symbol Servers. See Debugging Symbols.
To debug a service
1. Build your service in the Debug configuration.
2. Install your service. For more information, see How to: Install and Uninstall Services.
3. Start your service, either from Ser vices Control Manager , Ser ver Explorer , or from code. For more
information, see How to: Start Services.
4. Start Visual Studio with administrative credentials so you can attach to system processes.
5. (Optional) On the Visual Studio menu bar, choose Tools , Options . In the Options dialog box, choose
Debugging , Symbols , select the Microsoft Symbol Ser vers check box, and then choose the OK
button.
6. On the menu bar, choose Attach to Process from the Debug or Tools menu. (Keyboard: Ctrl+Alt+P)
The Processes dialog box appears.
7. Select the Show processes from all users check box.
8. In the Available Processes section, choose the process for your service, and then choose Attach .
TIP
The process will have the same name as the executable file for your service.
NOTE
You are now in debug mode.
3. In the Application tab of the project's properties, set the Output type to Console Application .
4. Choose Star t Debugging (F5).
5. To run the program as a Windows Service again, install it and start it as usual for a Windows Service. It's
not necessary to reverse these changes.
In some cases, such as when you want to debug an issue that occurs only on system startup, you have to use the
Windows debugger. Download the Windows Driver Kit (WDK) and see How to debug Windows Services.
See also
Introduction to Windows Service Applications
How to: Install and Uninstall Services
How to: Start Services
Debugging a Service
How to: Log Information About Services
10/18/2022 • 3 minutes to read • Edit Online
WARNING
This documentation isn't for the latest version of Windows Service. For the latest content on Windows Services using
BackgroundService and the Worker Service template, see:
Worker Services in .NET
Create a Windows Service using BackgroundService
By default, all Windows Service projects have the ability to interact with the Application event log and write
information and exceptions to it. You use the AutoLog property to indicate whether you want this functionality in
your application. By default, logging is turned on for any service you create with the Windows Service project
template. You can use a static form of the EventLog class to write service information to a log without having to
create an instance of an EventLog component or manually register a source.
The installer for your service automatically registers each service in your project as a valid source of events with
the Application log on the computer where the service is installed, when logging is turned on. The service logs
information each time the service is started, stopped, paused, resumed, installed, or uninstalled. It also logs any
failures that occur. You do not need to write any code to write entries to the log when using the default behavior;
the service handles this for you automatically.
If you want to write to an event log other than the Application log, you must set the AutoLog property to false ,
create your own custom event log within your services code, and register your service as a valid source of
entries for that log. You must then write code to record entries to the log whenever an action you're interested in
occurs.
NOTE
If you use a custom event log and configure your service application to write to it, you must not attempt to access the
event log before setting the service's ServiceName property in your code. The event log needs this property's value to
register your service as a valid source of events.
NOTE
By default, this property is set to true . You do not need to set this explicitly unless you are building more
complex processing, such as evaluating a condition and then setting the AutoLog property based on the result of
that condition.
this.AutoLog = false;
Me.AutoLog = False
NOTE
You must set AutoLog to false in order to use a custom log.
NOTE
In this code example, an instance of an EventLog component is named eventLog1 ( EventLog1 in Visual Basic).
If you created an instance with another name in step 2, change the code accordingly.
public UserService2()
{
eventLog1 = new System.Diagnostics.EventLog();
// Turn off autologging
this.AutoLog = false;
// create an event source, specifying the name of a log that
// does not currently exist to create a new, custom log
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource","MyLog");
}
// configure the event log instance to use this source name
eventLog1.Source = "MySource";
eventLog1.Log = "MyLog";
}
See also
Introduction to Windows Service Applications
Troubleshooting: Debugging Windows Services
10/18/2022 • 2 minutes to read • Edit Online
WARNING
This documentation isn't for the latest version of Windows Service. For the latest content on Windows Services using
BackgroundService and the Worker Service template, see:
Worker Services in .NET
Create a Windows Service using BackgroundService
When you debug a Windows service application, your service and the Windows Ser vice Manager interact.
The Ser vice Manager starts your service by calling the OnStart method, and then waits 30 seconds for the
OnStart method to return. If the method does not return in this time, the manager shows an error that the
service cannot be started.
When you debug the OnStart method as described in How to: Debug Windows Service Applications, you must
be aware of this 30-second period. If you place a breakpoint in the OnStart method and do not step through it in
30 seconds, the manager will not start the service.
See also
How to: Debug Windows Service Applications
Introduction to Windows Service Applications
Troubleshooting: Service Application Won't Install
10/18/2022 • 2 minutes to read • Edit Online
WARNING
This documentation isn't for the latest version of Windows Service. For the latest content on Windows Services using
BackgroundService and the Worker Service template, see:
Worker Services in .NET
Create a Windows Service using BackgroundService
If your service application will not install correctly, check to make sure that the ServiceName property for the
service class is set to the same value as is shown in the installer for that service. The value must be the same in
both instances in order for your service to install correctly.
NOTE
You can also look at the installation logs to get feedback on the installation process.
You should also check to determine whether you have another service with the same name already installed.
Service names must be unique for installation to succeed.
See also
Introduction to Windows Service Applications