Topshelf允許我們快速的開發、調試和部署windows服務。
官方網站
Install-Package Topshelf
Install-Package Topshelf.Log4Net
雖然安裝Topshelf.Log4Net不是必須的,不過建議安裝。
ServiceRunner.cs
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Threading;using System.IO;using Topshelf;using log4net;using log4net.Config;namespace WHTR.Demos.Topshelf{ public sealed class ServiceRunner : ServiceControl, ServiceSuspend { PRivate static ILog Logger = LogManager.GetLogger(typeof(Program)); private Timer timer; static ServiceRunner() { var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"); xmlConfigurator.ConfigureAndWatch(logCfg); } public bool Start(HostControl hostControl) { this.timer = new Timer(new TimerCallback(this.PrintMessage), null, 1000, 1000); return true; } public bool Stop(HostControl hostControl) { throw new NotImplementedException(); } public bool Continue(HostControl hostControl) { throw new NotImplementedException(); } public bool Pause(HostControl hostControl) { throw new NotImplementedException(); } private void PrintMessage(object state) { Logger.Info(DateTime.Now); } }}備注:要實現的接口及方法名意義非常明顯,這里就不做過多說明了。
Program.cs
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Topshelf;using Topshelf.ServiceConfigurators;namespace TopshelfDemos{ class Program { static void Main(string[] args) { HostFactory.Run(x => { //x.UseLog4Net("~/log4net.config"); x.Service<ServiceRunner>(); x.SetDescription("TopshelfDemos說明"); x.SetDisplayName("TopshelfDemos顯示名稱"); x.SetServiceName("TopshelfDemos服務名稱"); x.EnablePauseAndContinue(); }); } }}以前以為開發Windows服務是多么高大上的東西,沒想到這么簡單。就兩步,引用Topshelf.dll,然后實現接口,完成。
新聞熱點
疑難解答