标签:ring wrapper code tar des window https 内容 目录
Topshelf可用于创建和管理Windows服务。其优势在于不需要创建windows服务,创建控制台程序就可以。便于调试。
1、官网:http://topshelf-project.com/
2、官方文档:https://topshelf.readthedocs.io/en/latest/
3、github地址:https://github.com/Topshelf/Topshelf
1、创建控制台程序“Topshelf测试”,Nuget中引入Topshelf,如图所示:
也可以用Nuget的命令行引入,命令如下:
2、在项目中添加类,命名为:TopshelfTest
内容如下:
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"); } }
3、在Main函数中加入如下代码:
public static void Main(string[] args) { 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()); }); }); }
4、运行程序,输出如下,每秒中会执行一次Run函数,也就会打印一次“hello Topshelf”
5、安装服务:
以管理员权限打开cmd命令,管理服务的命令如下:
启动服务:
安装后可以看到服务中出现了安装的服务:
using System; using System.Timers; using Topshelf; namespace Topshelf测试 { public class Program { public static void Main(string[] args) { 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()); }); }); } } 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"); } } }
标签:ring wrapper code tar des window https 内容 目录
原文地址:http://www.cnblogs.com/dayang12525/p/7851230.html