Recently, due to work needs, I have written some Windows ServicesProgramAnd I have some experience.
Currently, I know that there are three ways to create a Windows Service:
A. Use the. NET Framework class servicebase
B. Use the topshelf component
C. Use the gadgets instsrv and srvany
The following three methods are used to create a Windows service program. The program function is to record logs in the program directory every five seconds:
A. Use the. NET Framework class servicebase
Features: simple and compatible
Implemented by inheriting the. NET Framework class servicebase
Step 2: Create a Windows Service
Public Partial Class Service1: servicebase { Readonly Timer _ timer; Private Static Readonly String Filename = path. getdirectoryname (assembly. getexecutingassembly (). Location) + @" \ " + " Test.txt " ; Public Service1 () {initializecomponent (); _ Timer = New Timer ( 5000 ) {Autoreset = True , Enabled = True }; _ Timer. elapsed + = Delegate ( Object Sender, elapsedeventargs e ){ This . Witre ( String . Format ( " Run datetime {0} " , Datetime. Now ));};} Protected Override Void Onstart ( String [] ARGs ){ This . Witre ( String . Format ( " Start datetime {0} " , Datetime. Now ));} Protected Override Void Onstop (){ This . Witre ( String . Format ( " Stop datetime {0} " , Datetime. Now) + Environment. newline );} Void Witre ( String Context) {streamwriter SW =File. appendtext (filename); Sw. writeline (context); Sw. Flush (); Sw. Close ();}}
Step 2: add an installer
[Runinstaller ( True )] Public Partial Class Installer1: system. configuration. Install. installer { Private Serviceinstaller; Private Serviceprocessinstaller processinstaller; Public Installer1 () {initializecomponent (); processinstaller = New Serviceprocessinstaller (); serviceinstaller = New Serviceinstaller (); processinstaller. Account = Serviceaccount. LocalSystem; serviceinstaller. starttype = Servicestartmode. Automatic; serviceinstaller. servicename = " My_windowsservice " ; Serviceinstaller. Description = " Windowsservice_description " ; Serviceinstaller. displayname = " Windowsservice_displayname " ; Installers. Add (serviceinstaller); installers. Add (processinstaller );}}
Step 2: Install and uninstall
CMD command
Installutil windowsservice_test.exe (install Windows Service)
Installutil/u windowsservice_test.exe (uninstall Windows Service)
CodeDownload: http://files.cnblogs.com/aierong/WindowsService_test.rar
B. Use the topshelf component
Features: simple code, open-source components, Windows Services can run multiple instances
Topshelf is an open-source cross-platform service framework, supporting windows and mono, just a few lines of code can be built a very convenient to use of the service.
Step 2: reference the Assembly topshelf. dll and log4net. dll
Step 2: create a service class myclass, which contains two methods: Start and Stop, and a timer, which writes characters to the text file every five seconds.
Public Class Myclass { Readonly Timer _ timer; Private Static Readonly String Filename = directory. getcurrentdirectory () + @" \ " + " Test.txt " ; Public Myclass () {_ Timer = New Timer ( 5000 ) {Autoreset = True , Enabled = True }; _ Timer. elapsed + = Delegate ( Object Sender, elapsedeventargs e ){ This . Witre ( String . Format ( " Run datetime {0} " , Datetime. Now ));};} Void Witre ( String Context) {streamwriter SW = File. appendtext (filename); Sw. writeline (context); Sw. Flush (); Sw. Close ();} Public Void Start (){ This . Witre ( String . Format ( " Start datetime {0} " , Datetime. Now ));} Public Void Stop (){ This . Witre ( String . Format ( " Stop datetime {0} " , Datetime. Now) + Environment. newline );}}
Step 2: Use topshelf to host our services. It mainly describes how topshelf sets the configuration of our services and how to call methods when starting and stopping services.
Class Program { Static Void Main ( String [] ARGs) {hostfactory. Run (x => {X. Service <Myclass> (S) => {S. setservicename ( " Ser " ); S. constructusing (name => New Myclass (); S. whenstarted (t) => T. Start (); S. whenstopped (t) => T. Stop () ;}); X. runaslocalsystem (); // Service Description X. setdescription ( " Topshelf_description " ); // Service display name X. setdisplayname (" Topshelf_displayname " ); // Service name X. setservicename ( " Topshelf_servicename " );});}}
Step 2: cmd command
Leleapp_topshelf.exe install (install Windows Services)
Leleapp_topshelf.exe uninstall (uninstall Windows Service)
Code download: http://files.cnblogs.com/aierong/ConsoleApp_Topshelf.rar
C. Use the gadgets instsrv and srvany
Features of this method: the code is super simple, the windowsform program is enough, and supports program interaction (my favorite features). It seems that Windows 7 is not supported, and XP win2003 is supported.
First, we will introduce two gadgets:
Instsrv.exe: used to install and uninstall executable services
Srvany.exe: Used to run any exe program as a Windows Service
These two tools are both practical gadgets of the Microsoft Windows resource kits tool set.
Can you get http://www.microsoft.com/en-us/download/details.aspx by downloading and installing Microsoft Windows resource kits? Id = 17657
Step 2: Create a windowsform Program
Public Partial Class Form1: FORM {timer _ timer; Private Static Readonly String Filename = application. startuppath + @" \ " + " Test.txt " ; Public Form1 () {initializecomponent ();} Private Void Form1_load (Object Sender, eventargs e) {_ Timer = New Timer () {Enabled = True , Interval = 5000 }; _ Timer. tick + = Delegate ( Object _ Sender, eventargs _ e ){ This . Witre (String . Format ( " Run datetime {0} " , Datetime. Now ));};} Void _ Timer_tick ( Object Sender, eventargs e ){ Throw New Notimplementedexception ();} Void Witre ( String Context) {streamwriter SW = File. appendtext (filename); Sw. writeline (context); Sw. Flush (); Sw. Close ();} Private Void Button#click ( Object Sender, eventargs e) {MessageBox. Show ( " Hello " );}}
Step 2: Install and uninstall
The installation steps are as follows:
(1) Open CMD and enter the following content. Here, windowsforms_windowsservice is the name of the service you want to create.
Format: absolute directory path \ instsrv windowsforms_windowsservice directory absolute path \ srvany.exe
For example:
D: \ tempwork \ win \ debug \ instsrv.exe windowsforms_windowsservice D: \ tempwork \ win \ debug \ srvany.exe
(2) Regedit open the Registry Editor and find the following directory:
HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Services \ windowsforms_windowsservice
(3) Right-click windowsforms_windowsservice and create an "item" named "Parameters"
(4) left-click "Parameters" and Right-click on the right side to create a "string value" (reg_sz) named "application ", enter the absolute path of the executable file under the directory + file name in the value data
For example:
D: \ tempwork \ win \ debug \ windowsformsapplication_exe.exe
(5) Open the services. msc service control panel, find the windowsforms_windowsservice Service, right-click-properties-log on, and select "allow services to interact with the desktop"
Start the service and you can see the program interface
Uninstall Service
D: \ tempwork \ win \ debug \ instsrv.exe windowsforms_windowsservice remove
Code download: http://files.cnblogs.com/aierong/WindowsFormsApplication_Exe.rar