WriteWindowsThe service is a relatively advanced programming technology, and a lot of internal useWindowsThe core functions of the operating system, but Microsoft. NetThe Framework has well encapsulated these technical details so that we can easily use them.C #Write your ownWindowsService, the basic process is generally
1.CreateC #Engineering. CreateEXEProject, which can beWinformOr in the command line format. AddSystem. serviceprocess. dllAndSystem. configuration. Install. dll.
2. Create a service class . Adds a class that inherits System. serviceprocess. servicebase Type, which is set in the constructor Servicename Attribute to specify the name of the service. Then reload its Onstart Method to respond to Service Startup events, reload Onstop Method to respond to service stop events, reload Onpause Method to respond to the service suspension event, reload Oncontinue Method to respond to events that restore services. When you reload these methods, you must return them immediately. Long operations are not allowed. If the processing time is too long Windows The Service Manager may think that WindowsAn error is returned when the service stops responding. Therefore, we can use a thread for actual work. Onstart Method creation thread, Onstop Method to close the thread, Onpause Method to suspend the thread, and Oncontinue Method to restore the running thread.
3.Start the service. InMainCall the"System. serviceprocess. servicebase. Run (Instance of the Custom Service Class)To run the service. For example,System. serviceprocess. servicebase. Run (New myservice ())", HereMyserviceIs inherited fromServicebase.
4. Install services . Adds a new class that inherits from System. configuration. Install. Installer Type, which is used in combination with Microsoft . Net The built-in installation command line tool Installutil.exe . We add System. componentmodel. runinstallerattribute Feature, and use it in its constructor System. serviceprocess. serviceinstaller Object and System. serviceprocess. serviceprocessinstaller The installation information of the service provided to the system.ProgramAfter compilation, we can use the command line" Installutil.exe exe File Name Direction Windows The Service Manager registers the service and can use the command line" Installutil.exe/u exe File Name "From Windows Log out of the service in the Service Manager.
5.Write a service client. This is an optional process based on the actual situation, becauseWindowsThe Service has no user interface, so we can write a program with user interface to display and ControlWindowsService data and system settings. For exampleMs SQL ServerThe database engine exists as a service, whileSQL ServerEnterprise Manager is a client software.