The. NET Framework provides a ready-made class library that makes it easy to install, uninstall, start, stop, and get running status for Windows services. These classes are under the System.ServiceProcess namespace.
Installing the Window Service
using New Assemblyinstaller ()) { true; = Servicefilepath; // Servicefilepath is the full path to the Windows service executable file New Hashtable (); Installer. Install (savedstate); Installer.Commit (savedstate); }
Uninstalling Windows Services
using New Assemblyinstaller ()) { true; = Servicefilepath; Installer. Uninstall (null); }
Start the Windows service
// use Servicecontroller.getservices () to get a list of Windows services to determine if a service exists // ServiceName is the registered Windows service name using New ServiceController (ServiceName)) { if (control. Status = = servicecontrollerstatus.stopped) { control. Start (); } }
Keng
Everything seems very simple, slightly pits, Servicecontroller.start method (note is not startasync), looks like a synchronous method, if the service fails to start, it is logically thrown. In reality, the Start method returns immediately without waiting for the service's startup result. There are only two scenarios in which an exception occurs in a method note:
System.ComponentModel.Win32Exception: An error occurred while accessing the system API.
System.InvalidOperationException: Service not found.
The Start method does not know anything about startup failures caused by other situations, such as missing files and internal errors within the service application.
The ServiceController class has a wait method that blocks the current thread waiting for the service to reach the specified state, and can also set the wait time-out period, which is useful, but not ideal. How can I get information about startup failure when it fails to start?
A wretched way.
Windows service startup, whether successful or unsuccessful, logs a Windows log that can be implemented with monitoring of Windows logs:
Start listening to the Windows log before calling the Servicecontroller.start method:
New EventLog ("application"true+ = Log_entrywritten;
In the EntryWritten event handler, determine the Windows log type and learn about the Windows service startup situation:
Private voidLog_entrywritten (Objectsender, Entrywritteneventargs e) {EventLogEntry log=E.entry; if(log. Source = =_currentsection.servicename) { if(log. EntryType = =eventlogentrytype.information) {//Startup Success } Else { //failed to startMessageBox.Show (log. Message); } _eventlog.dispose (); _eventlog=NULL; } }
Here also a slightly pit point, according to the General Event Development Convention, sender parameters should be the subject of the event, where to think should be EventLog class instance, but in fact sender is an example of eventloginternal class, unfortunately, This class is not publicly accessible, and no direct association with the EventLog class has been found.
C # Managing Windows Services