Topshelf官网文档:https://topshelf.readthedocs.io/en/latest/configuration/quickstart.html
1. vs创建控制台程序
2. NuGet安装Topshelf
3. 代码
public static void Main() { try { 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("接收充电桩监听信息,并保存数据库"); //7 x.SetDisplayName("chargeMonitorService"); //8 x.SetServiceName("chargeMonitorService"); //9 }); //10 var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode()); //11 Environment.ExitCode = exitCode; } catch (Exception ex) { Console.WriteLine(ex.Message); } } public class TownCrier { //readonly Timer _timer; TCPService service; string IP; int Port; public TownCrier() { //_timer = new Timer(1000) { AutoReset = true }; //_timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now); IP = xml.getValue("IP"); Port = int.Parse(xml.getValue("Port")); } public void Start() { service = new TCPService(IP, Port); //_timer.Start(); } public void Stop() { service.close(); //_timer.Stop(); } }
4. 安装服务
管理员权限打开控制台
进入项目输出目录
启动文件名+" "+ install
安装服务 install
卸载服务 uninstall
注: F5运行可以用来调试, cmd非管理员启动会安装失败