引用
新建一个控制台程序,使用Nuget添加Topshelf的引用。程序安装指令:
- Install-Package Topshelf
配置
这里我们添加一个ServiceMain类,包含一个构造函数,服务的启动,停止,终止,继续方法:
public class SerivceMain { public SerivceMain() { //add you code } public void Start() { //add you code } public void Stop() { //add you code } public void Pause() { //add you code } public void Continue() { //add you code } }
在Main函数中注册下刚才写的那个类的几个行为:
1 HostFactory.Run(x => 2 { 3 x.Service<ServiceMain>(s => 4 { 5 s.ConstructUsing(name => new ServiceMain()); 6 s.WhenStarted(tc => tc.Start()); 7 s.WhenStopped(tc => tc.Stop()); 8 s.WhenPaused(tc => tc.Pause()); 9 s.WhenContinued(tc => tc.Continue()); 10 }); 11 x.RunAsLocalService(); 12 13 x.SetDescription("后台服务"); 14 x.SetDisplayName("SerivceDisplayName"); 15 x.SetServiceName("ServiceName"); 16 });
就大功告成了