.NET开发Windows Service程序

在实际项目开发过程中,会经常写一些类似定时检查,应用监控的应用。这类应用在windows平台通常都会写成window service程序。

在百度上搜索一下'c#开发windows service',基本都是使用VS windows服务的模板来开发,使用VS Attach到服务的进程来调试,使用InstallUtil工具来安装windows服务。还是有些麻烦的。

本文主要介绍一下使用Topshelf开源框架来创建windows服务,简单、方便和快捷。官方文档也很简单,花半个小时过一遍即可https://topshelf.readthedocs.io/en/latest/configuration/quickstart.html

创建一个控制台程序,安装Topshelf到工程中

Install-Package Topshelf
Install-Package Topshelf.NLog // for Logging

程序示例

using System;
using System.Timers;
using Topshelf;

namespace TopshelfFirstDemo
{
    public class TownCrier
    {
        readonly Timer _timer;
        public TownCrier()
        {
            _timer = new Timer(1000) { 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(); }
    }

    class Program
    {
        static int Main(string[] args)
        {
            var exitCode = HostFactory.Run(x =>
             {
                 x.UseNLog();

                 x.Service<TownCrier>(s =>
                 {
                     s.ConstructUsing(name => new TownCrier());
                     s.WhenStarted(tc => tc.Start());
                     s.WhenStopped(tc => tc.Stop());

                 });
                 x.RunAsLocalSystem();

                 x.SetDescription("A test service using Topshelf");
                 x.SetDisplayName("TestTopshelf");
                 x.SetServiceName("TestTopshelf");

                 x.OnException(ex =>
                 {
                    // Logging
                 });
             });

            Console.WriteLine(exitCode);

            return (int)exitCode;
        }
    }
}

可通过设置Service各种参数来设置开发的windows service,关于Service的参数配置,请参考官方文档。

安装windows service

CD到示例程序Debug/Release bin目录

列出各命令

TopshelfFirstDemo.exe help

安装服务

TopshelfFirstDemo.exe install

卸载服务

TopshelfFirstDemo.exe uninstall

start和stop服务的方式有很多了,通过

  1. 到windows服务界面(cmd -> services.msc)手动启停
  2. net start/stop TestTopshelf
  3. TopshelfFirstDemo.exe start/stop
原文地址:https://www.cnblogs.com/codesee/p/6242154.html