欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#用Topshelf创建Windows服务的步骤分享

程序员文章站 2022-09-02 10:07:21
一、项目创建创建一个控制台应用程序,项目右键->管理 nuget 程序包->topshelft及topshelf.log4net。二、topshelf配置 一般来说,服务都会设置每隔多长时...

一、项目创建

创建一个控制台应用程序,项目右键->管理 nuget 程序包->topshelft及topshelf.log4net。

C#用Topshelf创建Windows服务的步骤分享 

C#用Topshelf创建Windows服务的步骤分享   

二、topshelf配置

    一般来说,服务都会设置每隔多长时间执行一次任务,这里使用system.threading.timer来做个简单的日志记录,将日志写入到debug\log文件夹下。

    2.1、log4net配置

    新建一个log4net.config的配置文件,在其属性的复制到输出目录项下选择始终复制。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <configsections>
 <section name="log4net" type="log4net.config.log4netconfigurationsectionhandler, log4net" />
 </configsections>
 <log4net>
 <!-- console部分log输出格式的设定 -->
 <appender name="consoleappender" type="log4net.appender.consoleappender">
  <layout type="log4net.layout.patternlayout">
  <conversionpattern value="%date [%thread] %-5level %logger - %message %newline" />
  </layout>
 </appender>
 <appender name="rollinglogfileappender" type="log4net.appender.rollingfileappender">
  <file value="log\"/>
  <appendtofile value="true"/>
  <maxsizerollbackups value="10"/>
  <maximumfilesize value="1mb"/>
  <rollingstyle value="date"/>
  <datepattern value='yyyy-mm-dd".log"' />
  <staticlogfilename value="false"/>
  <!--最小锁定模型以允许多个进程可以写入同一个文件-->
  <param name="lockingmodel" type="log4net.appender.fileappender+minimallock" />
  <layout type="log4net.layout.patternlayout">
  <conversionpattern value="%date %-5level %logger - %message %newline"/>
  </layout>
 </appender>
 <root>
  <level value="all" />
  <appender-ref ref="consoleappender" />
  <appender-ref ref="rollinglogfileappender" />
 </root>
 </log4net>
</configuration>

    2.2、topshelfservice

    新建一个topshelfservice类:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading;
using system.threading.tasks;
using topshelf;
using topshelf.logging;

namespace linkto.test.topshelfservice
{
  public class topshelfservice : servicecontrol
  {
    private static readonly logwriter logger = hostlogger.get<topshelfservice>();
    private static timer timerasync = null;
    private readonly int duetimeinterval = 1000 * 5; //单位:毫秒
    private readonly int periodinterval = 1000 * 5; //单位:毫秒

    /// <summary>
    /// 构造函数
    /// </summary>
    public topshelfservice()
    {
      timerasync = new timer(autoasynccallback, null, timeout.infinite, timeout.infinite);
    }

    /// <summary>
    /// 启动服务
    /// </summary>
    /// <param name="hostcontrol"></param>
    /// <returns></returns>
    public bool start(hostcontrol hostcontrol)
    {
      try
      {
        logger.info("hellotopshelf start");
        timerasync.change(duetimeinterval, periodinterval);
      }
      catch (exception ex)
      {
        logger.info(ex.message);
      }
      return true;
    }

    /// <summary>
    /// 停止服务
    /// </summary>
    /// <param name="hostcontrol"></param>
    /// <returns></returns>
    public bool stop(hostcontrol hostcontrol)
    {
      try
      {
        logger.info("hellotopshelf stop");
        if (timerasync != null)
        {
          timerasync.change(timeout.infinite, timeout.infinite);
          timerasync.dispose();
          timerasync = null;
        }
      }
      catch (exception ex)
      {
        logger.info(ex.message);
      }
      return true;
    }

    /// <summary>
    /// 回调函数
    /// </summary>
    /// <param name="state"></param>
    private void autoasynccallback(object state)
    {
      try
      {
        timerasync.change(timeout.infinite, timeout.infinite);
        logger.info("autoasynccallback执行开始");
        thread.sleep(1000 * 10);
      }
      catch (exception ex)
      {
        logger.errorformat("autoasynccallback执行异常:{0}", ex.message);
      }
      finally
      {
        timerasync.change(duetimeinterval, periodinterval);
        logger.info("autoasynccallback执行结束");
        logger.info(environment.newline);
      }
    }
  }
}

    2.3、配置和运行宿主服务

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
using topshelf;

namespace linkto.test.topshelfservice
{
  class program
  {
    static void main(string[] args)
    {
      hostfactory.run(x =>
      {
        x.uselog4net("log4net.config");
        x.runaslocalsystem();
        x.service(settings => new topshelfservice());
        //服务的描述
        x.setdescription("你好,topshelf!");
        //服务的显示名称
        x.setdisplayname("hello topshelf service");
        //服务名称
        x.setservicename("hellotopshelf");
      });
    }
  }
}

    三、安装与卸载

    3.1、安装服务

    在debug文件夹下面,创建一个"安装服务.bat"的批处理文件:

@echo on

rem 设置dos窗口的背景颜色及字体颜色
color 2f

rem 设置dos窗口大小 
mode con: cols=80 lines=25

@echo off
echo 请按任意键开始安装linkto.test.topshelfservice服务

rem 输出空行
echo.
pause

linkto.test.topshelfservice install
net start hellotopshelf

pause

    3.2、卸载服务

    在debug文件夹下面,创建一个"卸载服务.bat"的批处理文件:

@echo on

rem 设置dos窗口的背景颜色及字体颜色
color 2f

rem 设置dos窗口大小 
mode con: cols=80 lines=25

@echo off
echo 请按任意键开始卸载linkto.test.topshelfservice服务

rem 输出空行
echo.
pause

net stop hellotopshelf
linkto.test.topshelfservice uninstall

pause

    3.3、查看服务

    在运行中输入"services.msc"进入服务,即可看到新建的hellotopshelf服务:

C#用Topshelf创建Windows服务的步骤分享

    四、添加管理员权限要求

    项目右键->添加->新建项->应用程序清单文件。

C#用Topshelf创建Windows服务的步骤分享 

    将requestedexecutionlevel节点的level设置为"requireadministrator"。

<requestedexecutionlevel level="requireadministrator" uiaccess="false" />

总结

到此这篇关于c#用topshelf创建windows服务的文章就介绍到这了,更多相关c#用topshelf创建windows服务内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!