This articles explains the ServiceController. The ServiceController component is used to fetch the installed services and manipulate the state of the service. We can start and stop a service using the Service Controller and can pause and continue its functioning.
A Windows Service is formally known as am NT Service that creates a long-running executable application that runs on a Windows session. Windows Services can be started automatically when the computer boots, we can pause and restart too. These services have no user interface, this features makes the service ideal for use on a server. We can easily create a service by a Visual Studio project.
What SericeController class is
A ServiceController class represents a Windows service that allows us to connect to a running or stopped service. We can also change the state of the service and get information about the service. A ServiceController class is connected with our already installed class and change the behavior of our existing services. When we create an instance of the Service controller class, we set the property that interacts with our installed Windows Service. We can understand the ServiceController as an administartive purpose tool that mainly handle the Service Control Manager (SCM).
Example
Let's try to understand it with an example.
If we need to fetch all the installed services in our computer then we can use the following:
- using System;
- using System.ServiceProcess;
- using System.Diagnostics;
- using System.Threading;
-
- namespace ServiceControllerDemo
- {
- class Program
- {
- public enum ServiceCustomCommands
- {
- StopWorker = 128,
- RestartWorker,
- CheckWorker
- };
- static void Main(string[] args)
- {
- ServiceController[] objService;
- objService = ServiceController.GetServices();
- }
- }
- }
After exploring the Service.
Now, let's try to control a service. In this example we are only getting the status of the service, but we can also manipulate the service like start, pause and and so on.
- using System;
- using System.ServiceProcess;
- using System.Diagnostics;
- using System.Threading;
-
- namespace ServiceControllerDemo
- {
- class Program
- {
- public enum ServiceCustomCommands
- {
- StopWorker = 128,
- RestartWorker,
- CheckWorker
- };
- static void Main(string[] args)
- {
- ServiceController[] objService;
- objService = ServiceController.GetServices();
- foreach (ServiceController SController in objService)
- {
- if (SController.ServiceName == "AdobeARMservice")
- {
- ServiceController sc = new ServiceController("Adobe Acrobat Update Service");
- Console.WriteLine("Status = " + sc.Status);
- Console.WriteLine("Pause and Continue ? = " + sc.CanPauseAndContinue);
- Console.WriteLine("ShutDown ? = " + sc.CanShutdown);
- Console.WriteLine("Stop ? = " + sc.CanStop);
-
-
-
- }
- }
-
- }
- }
- }
Summary
In this article we saw the benefits of the ServiceController class and its uses. I hope you like this article.