.NET开发Windows Service程序 - Topshelf
在實際項目開發(fā)過程中,會經(jīng)常寫一些類似定時檢查,應(yīng)用監(jiān)控的應(yīng)用。這類應(yīng)用在windows平臺通常都會寫成window service程序。
在百度上搜索一下'c#開發(fā)windows service',基本都是使用VS windows服務(wù)的模板來開發(fā),使用VS Attach到服務(wù)的進(jìn)程來調(diào)試,使用InstallUtil工具來安裝windows服務(wù)。還是有些麻煩的。
本文主要介紹一下使用Topshelf開源框架來創(chuàng)建windows服務(wù),簡單、方便和快捷。官方文檔也很簡單,花半個小時過一遍即可https://topshelf.readthedocs.io/en/latest/configuration/quickstart.html
創(chuàng)建一個控制臺程序,安裝Topshelf到工程中
Install-Package Topshelf Install-Package Topshelf.NLog // for Logging程序示例
using System; using System.Timers; using Topshelf;namespace TopshelfFirstDemo {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(); }}class Program{static int Main(string[] args){var exitCode = HostFactory.Run(x =>{x.UseNLog();x.Service<TownCrier>(s =>{s.ConstructUsing(name => new TownCrier());s.WhenStarted(tc => tc.Start());s.WhenStopped(tc => tc.Stop());});x.RunAsLocalSystem();x.SetDescription("A test service using Topshelf");x.SetDisplayName("TestTopshelf");x.SetServiceName("TestTopshelf");x.OnException(ex =>{// Logging});});Console.WriteLine(exitCode);return (int)exitCode;}} }可通過設(shè)置Service各種參數(shù)來設(shè)置開發(fā)的windows service,關(guān)于Service的參數(shù)配置,請參考官方文檔。
安裝windows service
CD到示例程序Debug/Release bin目錄
列出各命令
TopshelfFirstDemo.exe help安裝服務(wù)
TopshelfFirstDemo.exe install卸載服務(wù)
TopshelfFirstDemo.exe uninstallstart和stop服務(wù)的方式有很多了,通過
?
轉(zhuǎn)載于:https://www.cnblogs.com/codesee/p/6242154.html
總結(jié)
以上是生活随笔為你收集整理的.NET开发Windows Service程序 - Topshelf的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Idris趋近发布1.0版
- 下一篇: Net分布式系统之四:RabbitMQ消