[Solution] Microsoft Windows 服务(2) 使用Topshelf创建Windows服务

  除了通过.net提供的windows服务模板外,Topshelf是创建Windows服务的另一种方法。

  

  官网教程:http://docs.topshelf-project.com/en/latest/configuration/quickstart.html

 

优点:

    1.可以直接调试运行。

    2.命令更方便。

    3.Topshelf是一个开源的跨平台的宿主服务框架,支持Windows和Mono

 

 

 

下载:

  Install-Package Topshelf 

 

  

开发:

  0.创建服务 1.安装 2.启动 3.停止 4.卸载 5.调试服务 6.监控服务

 

创建服务:

   1.使用Topshelf创建服务非常简单。构建任何一个class ,提供一个启动和停止的方法即可。

   2.本节使用System.Timers.Timer做定时任务处理

class MyService
    {
        readonly Timer timer = new Timer();
        public MyService()
        {
            timer.Interval = 1000;
            timer.Elapsed += (s, e) => File.AppendAllText("d:\\1.txt",DateTime.Now.ToLongTimeString()+"\r\n");
        }
        public void Start()
        {
            timer.Start();
        }
        public void Stop()
        {
            timer.Stop();
        }
    }

  当创建完一个服务后,需要配置指定服务和指定启动停止的方法。

class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                //要配置的服务
                x.Service<MyService>(c =>
                {
                    c.ConstructUsing(name => new MyService());
                    c.WhenStarted(s => s.Start());
                    c.WhenStopped(s => s.Stop());
                });
                //服务的运行身份
                x.RunAsLocalSystem();

                x.SetDescription("服务描述");
                x.SetDisplayName("显示名称");
                x.SetServiceName("服务名称");
            });
        }
    }

 

 

安装:

    a.cd 定位到程序目录.        b.程序以管理员身份运行        c.程序名 install

    

 

启动:

    start 程序名

 

停止:

  

     stop 程序名

 

卸载:

    uninstall 程序名

 

 

调试服务:

  直接运行,即可调试

 

监控:

使用ServiceController来获取服务状态或对服务进行控制。

这个类可以获取服务的状态,属性,对服务也可以进行启动,停止操作

 

 

代码下载:点击下载

posted @ 2015-07-02 15:35  Never、C  阅读(483)  评论(0编辑  收藏  举报