About Topshelf
Topshelf is a framework for hosting services written using the. NET framework. The creation of services is simplified, allowing developers to create a simple console application so can be installed a s a service using Topshelf. The reason for this is simple:it are far easier to debug a console application than a service. And once the application is tested and ready for production, topshelf makes it easy to install the application as a Servic E.
Example first step: Create a new C # console application. Step two: Use Nuget to refer to Topshelf and log4net. Step three: Post the code below.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingsystem.timers;usingtopshelf;usingtopshelf.builders;usingtopshelf.configurators;usingtopshelf.hostconfigurators;namespacetopshelfstudy{ Public Sealed classTimereporter {Private ReadOnlyTimer _timer; PublicTimereporter () {_timer=NewTimer ( +) {AutoReset =true }; _timer. Elapsed+ = (sender, EventArgs) = Console.WriteLine ("Current time: {0}", DateTime.Now); } Public voidStart () {_timer. Start (); } Public voidStop () {_timer. Stop (); } } classProgram {Static voidMain (string[] args) {Hostfactory.run (x={X.service<TimeReporter> (s ={s.constructusing (Settings=NewTimereporter ()); s.whenstarted (tr=tr. Start ()); s.whenstopped (tr=tr. Stop ()); }); X.runaslocalsystem (); X.setdescription ("timed reporting Time"); X.setdisplayname ("time-reporting device"); X.setservicename ("Timereporter"); }); } }}
Fourth step: Compile, Release build. Copy the Release folder to drive C. Fifth step: Run cmd as Administrator, install, start.
SampleWindowsService.exe Install
Start
SampleWindowsService.exe start
It's also handy if you want to uninstall
SampleWindowsService.exe Uninstall
The effect is as follows:
Finally the Windows Service does not have Console.WriteLine, we can output the output information to the file.
New StreamWriter ("e:\\temp\\log.log"true; Console.setout (SW);
Reference website:
Http://www.cnblogs.com/shanyou/archive/2011/05/04/2037008.html
Http://www.cnblogs.com/happyframework/p/3601995.html
Http://www.cnblogs.com/chenxizhang/archive/2010/04/21/1716773.html
Thanks for browsing!