写了一两天,才发现组长给的原始代码原本就有Topshelf,还是写出来提示我topshelf不明确哪个版本的使用,莫名尴尬。
1、项目的主要运行代码
HostFactory.Run(x =>{x.RunAsLocalSystem();x.SetDescription("topshelf测试");x.SetDisplayName("topshelftest");x.SetServiceName("topshelftest");x.Service<TopshelfTest>(s =>{s.ConstructUsing(name => new TopshelfTest());s.WhenStarted(tc => tc.Start());s.WhenStopped(tc => tc.Stop());});});
using System;
using System.Timers;namespace TopshelfDemo
{public class TopshelfTest{readonly Timer timer;public TopshelfTest(){timer = new Timer(1000) { AutoReset = true };timer.Elapsed += (sender, eventArgs) => { Run(); };}public void Start() { timer.Start(); }public void Stop() { timer.Stop(); }public static void Run(){Console.WriteLine("hello TopShelf");}}
}
2、服务安装、启动和卸载
使用管理员进入cmd
进入相应的文件夹位置
TopshelfDemo.exe install 注册
TopshelfDemo.exe start启动
TopshelfDemo.exe uninstall 卸载
win+R,输入services.msc查看