使用Topshelf创建Windows服务
1.Topshelf是创建Windows服务的另一种方法,Topshelf是一个开源的跨平台的宿主服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务宿主。
2.添加引用:Topshelf.dll
Topshelf.Log4Net.dll
3.最新版本下载地址:https://github.com/Topshelf/Topshelf/downloads
4.官方案例:
class Program { public static void Main() { 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 } } public class TownCrier { readonly Timer _timer; public TownCrier() { _timer = new Timer(5000) { 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(); } }
5.安装卸载方法:
安装:TopshelfDemo.exe install
启动:TopshelfDemo.exe start
卸载:TopshelfDemo.exe uninstall
6.安装完成后即可在,Windows服务里看到
![](https://images2015.cnblogs.com/blog/587177/201707/587177-20170713134526025-251021577.png)