概述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
沒錯,整個程序已經開發完了,接下來,只須要簡單配置一下,便可以當服務來使用了。安裝很方便:
安裝成功後,接下來,咱們就能夠看到服務裏多了一個服務: