This article reproduced: http://www.cnblogs.com/aierong/archive/2012/05/28/2521409.html
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
public class MyClass {readonly Timer _timer; private static readonly String FileName = directory.getcurrentdirectory () + @ "\" + "test.txt"; Public MyClass () {_timer = new timer () {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);} }
3rd Step: Use Topshelf to host our service, mainly topshelf how to set up our service configuration and method call when start and stop
Class program { static void Main (string [] args) { Hostfactory.run (x = = { x.service<my Class> ((s) = { s.setservicename ("Ser"); S.constructusing (name = new MyClass ()); S.whenstarted ((t) = T.start ()); S.whenstopped ((t) = T.stop ()); ); X.runaslocalsystem (); Description of the service x.setdescription ("topshelf_description"); The display name of the service x.setdisplayname ("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
Create a Windows service using Topshelf
Creating a Windows service with Topshelf briefly describes another way to create a Windows service, a foreigner article create a. NET Windows service in 5 steps with Topshelf uses Topshelf to create a Windows service by using the 5-step detailed introduction. Topshelf is an open-source, cross-platform hosting service framework that supports Windows and mono and can build a convenient service host with just a few lines of code.
Reference article: http://www.cnblogs.com/shanyou/archive/2009/11/24/1609862.html
Http://www.cnblogs.com/shanyou/archive/2011/05/04/2037008.html