C# 使用 Topshelf 创建Windows服务
本文写作的目的是,记录一种最简单开发 Windows 服务的方式– Topshelf 。使用前先下载依赖文件: Topshelf.dll Topshelf.4.2.0.zip 或者直接通过 Nuget 安装:Install-Package Topshelf
Topshelf 文档地址: https://topshelf.readthedocs.io/en/latest/configuration/quickstart.html
直接上代码
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() { var rc = 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 var exitCode = (int) Convert.ChangeType(rc, rc.GetTypeCode()); //11 Environment.ExitCode = exitCode; } }
安装服务 命令行安装 这里要注意:必须使用管理员方式运行命令行窗口!!
命令行窗口中会涉及到的命令(以程序 server.exe 举例,自行替换):
安装服务 server.exe install
启动服务 server.exe start
停止服务 server.exe stop
卸载服务 server.exe uninstall
参考文章