概述html
Topshelf是建立Windows服务的另外一种方法,老外的一篇文章Create a .NET Windows Service in 5 steps with Topshelf经过5个步骤详细的介绍使用使用Topshelf建立Windows 服务。Topshelf是一个开源的跨平台的宿主服务框架,支持Windows和Mono,只须要几行代码就能够构建一个很方便使用的服务宿主。git
引用安装github
一、官网:http://topshelf-project.com/ 这里面有详细的文档及下载windows
二、Topshelf的代码托管在http://github.com/topshelf/Topshelf/downloads ,能够在这里下载到最新的代码。app
三、新建一个项目,只须要引用Topshelf.dll 便可,为了日志输出显示,建议也同时引用Topshelf.Log4Net。程序安装命令框架
使用ui
官网文档给过来的例子很是简单,直接使用便可以跑起来,官网文档地址:http://docs.topshelf-project.com/en/latest/configuration/quickstart.htmlspa
public class TownCrier { readonly Timer _timer; public TownCrier() { _timer = new Timer(1000) {AutoReset = true}; _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now); } public void Start() { _timer.Start(); } public void Stop() { _timer.Stop(); } } public class Program { public static void Main() { HostFactory.Run(x => //1 { x.Service<TownCrier>(s => //2 { s.ConstructUsing(name=> new TownCrier()); //3 s.WhenStarted(tc => tc.Start()); //4 s.WhenStopped(tc => tc.Stop()); //5 }); x.RunAsLocalSystem(); //6 x.SetDescription("Sample Topshelf Host"); //7 x.SetDisplayName("Stuff"); //8 x.SetServiceName("Stuff"); //9 }); //10 } }
程序跑起来后,每隔一秒钟有输出,看到的效果以下:日志
配置运行code
没错,整个程序已经开发完了,接下来,只须要简单配置一下,便可以当服务来使用了。安装很方便:
安装成功后,接下来,咱们就能够看到服务里多了一个服务: