Topshelf的使用

 

一、简介

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的命令行引入,命令如下:

  • Install-Package Topshelf

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命令,管理服务的命令如下:

安装:Topshelf测试.exe install
启动:Topshelf测试.exe start
卸载:Topshelf测试.exe uninstall
 
执行命令需要切入到程序目录下,如图所示:
安装服务:

启动服务:

 
卸载服务:

 安装后可以看到服务中出现了安装的服务:

四、示例代码

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");
        }
    }
}

 

 

posted @ 2017-11-17 13:54  向萧  阅读(480)  评论(0编辑  收藏  举报