Recently due to work needs, wrote some Windows service programs, have some experience, I now summarize write out.
Currently I know that there are 3 ways to create a Windows service:
A. Leveraging the. NET Framework class ServiceBase
B. Using Component Topshelf
C. Using gadgets instsrv and Srvany
Below I use these 3 ways, respectively, to do a Windows service program, the program function is every 5 seconds to the program directory logging:
A. Leveraging the. NET Framework class ServiceBase
Features of the method: simple, good compatibility
implemented by inheriting the. NET Framework class ServiceBase
1th Step: Create a new Windows service
PublicPartialClassService1:servicebase {ReadOnlyTimer _timer;PrivateStaticReadOnlyString FileName = Path.getdirectoryname (assembly.getexecutingassembly (). Location) +@"\" +"Test.txt";PublicService1 () {InitializeComponent (); _timer =New Timer (5000) {AutoReset =True, Enabled =True}; _timer. Elapsed + =Delegate (Objectsender, Elapsedeventargs e) {This.witre (String. Format ("Run DateTime {0}", DateTime.Now)); }; }ProtectedOverridevoid OnStart (String[] args) {This.witre (String. Format ( "start DateTime {0}protected override Void OnStop () {this.witre ( string. Format (stop DateTime {0} Environment.NewLine);} void witre (string Context) {StreamWriter sw = File.appendtext (FileName); SW. WriteLine (context); Sw. Flush (); Sw. Close (); } }
2nd Step: Add Installer
[Runinstaller (True)]PublicPartialClassInstaller1:System.Configuration.Install.Installer {PrivateServiceInstaller ServiceInstaller;PrivateServiceProcessInstaller Processinstaller;PublicInstaller1 () {InitializeComponent (); Processinstaller =NewServiceProcessInstaller (); ServiceInstaller =new ServiceInstaller (); Processinstaller.account =< Span style= "color: #000000;" > Serviceaccount.localsystem; Serviceinstaller.starttype = servicestartmode.automatic; Serviceinstaller.servicename = "my_windowsservice< Span style= "color: #800000;" > " Serviceinstaller.description = " windowsservice_description "; Serviceinstaller.displayname = "windowsservice_ Displayname "; Installers.add (ServiceInstaller); Installers.add (Processinstaller); } }
3rd Step: Install, uninstall
CMD command
InstallUtil Windowsservice_test.exe (installing Windows Services)
installutil/u windowsservice_test.exe (uninstall Windows service)
Code Download: Http://files.cnblogs.com/aierong/WindowsService_test.rar
B. Using Component Topshelf
This approach features: code simple, open source components, Windows services can run multiple instances
Topshelf is an open-source, cross-platform service framework that supports Windows and mono, and allows you to build a service that is easy to use with just a few lines of code. Official website: http://topshelf-project.com
1th step: Referencing Assemblies TopShelf.dll and Log4net.dll
2nd step: Create a service class MyClass, which contains two methods start and stop, also includes a timer timer, every 5 seconds to the text file to write characters
PublicClassMyClass {ReadOnlyTimer _timer;PrivateStaticReadOnlyString FileName = Directory.GetCurrentDirectory () +@"\" +"Test.txt";PublicMyClass () {_timer =New Timer (5000) {AutoReset =True, Enabled =True}; _timer. Elapsed + =Delegate (Objectsender, Elapsedeventargs e) {This.witre (String. Format ("Run DateTime {0}", DateTime.Now)); }; }void Witre (StringContext) {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);}}
3rd Step: Use Topshelf to host our service, mainly topshelf how to set up our service configuration and method call when start and stop
Classprogram {Staticvoid Main (String[] args) {hostfactory.run (x ={x.service<myclass> (s) ={S.setservicename ("Ser"); S.constructusing (name =NewMyClass ()); S.whenstarted ((t) = T.start ()); S.whenstopped ((t) => T.stop ());}); X.runaslocalsystem (); // Description of the service x.setdescription ( "topshelf_description "); // "topshelf_displayname "); // service name X.setservicename ( "topshelf_servicename "
4th Step: cmd command
Consoleapp_topshelf.exe Install (installing Windows Services)
Consoleapp_topshelf.exe Uninstall (uninstall Windows service)
Code Download: Http://files.cnblogs.com/aierong/ConsoleApp_Topshelf.rar
C. Using gadgets instsrv and Srvany
This method features: Code super simple, WindowsForm program can, and support program interaction (I like the characteristics), as if not support Win7, support XP Win2003
2 gadgets are introduced first:
Instsrv.exe: Used to install and uninstall executable services
Srvany.exe: Used to run any EXE program as a Windows service
These 2 tools are a practical gadget for the Microsoft Windows Resource Kits Toolset
You can get http://www.microsoft.com/en-us/download/details.aspx?id=17657 by downloading and installing Microsoft Windows Resource Kits
1th Step: New WindowsForm Program
PublicPartialClassform1:form {Timer _timer;PrivateStaticReadOnlyString FileName = Application.startuppath +@"\" +"Test.txt";PublicForm1 () {InitializeComponent ();}Privatevoid Form1_Load (Objectsender, EventArgs e) {_timer =NewTimer () {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 button1_click ( object sender, EventArgs e) {MessageBox.Show ( "hello" );}
2nd step: Install, uninstall
The installation step of the service is 5 small steps:
(1) Open cmd, enter the following, where Windowsforms_windowsservice is the name of the service you want to create
Format: Directory absolute 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 locate the following directory
Hkey_local_machine\system\currentcontrolset\services\windowsforms_windowsservice
(3) Right-click Windowsforms_windowsservice, create an "item" with the name "Parameters"
(4) left mouse button click "Parameters", right click on the right mouse button, create a "string value" (REG_SZ), the name is "Application", the value data fill in the directory executable file absolute path + file name
For example:
D:\TempWork\win\Debug\WindowsFormsApplication_Exe.exe
(5) Open Services.msc Service Control Panel, find Windowsforms_windowsservice service, right mouse button-Properties-login, tick "Allow service to interact with desktop"
Start the service, 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
Create a Windows service (Windows Services) Summary of n ways