zoukankan      html  css  js  c++  java
  • 系统服务的最简单实现

       下面我告诉你,只需三个文件,即可完成一个系统服务。

          1.新建一个类,命名为TestService,并继承于

    System.ServiceProcess.ServiceBase。重启其中的OnStart方法和OnStop方法

          

     1 public class TestService:ServiceBase
     2     {
     3         protected override void OnStart(string[] args)
     4         {
     5             NLogHelper.Trace("OnStart");
     6         }
     7 
     8         protected override void OnStop()
     9         {
    10             NLogHelper.Trace("OnStop");
    11         }
    12     }

         2.新建一个类,命名为TestServiceInstaller,并继承于System.Configuration.Install

         

     1     [RunInstaller(true)]
     2     public class TestServiceInstaller : Installer
     3     {
     4         /// <summary>
     5         /// 安装一个进程
     6         /// </summary>
     7         private ServiceInstaller serviceInstaller;
     8         /// <summary>
     9         /// 安装一个服务
    10         /// </summary>
    11         private ServiceProcessInstaller processInstaller;
    12 
    13         /// <summary>
    14         /// Initializes a new instance of the <see cref="TestServiceInstaller"/> class.
    15         /// </summary>
    16         public TestServiceInstaller()
    17         {
    18             //致命用户类型
    19             processInstaller = new ServiceProcessInstaller {Account = ServiceAccount.LocalSystem};
    20             serviceInstaller = new ServiceInstaller
    21                                    {
    22                                        StartType = ServiceStartMode.Manual,//服务的启动类型:手动
    23                                        ServiceName = "TestService",//服务的名称
    24                                        Description = "这是TestService的描述",
    25                                        DisplayName = "这里是显示在系统服务中的名称"
    26                                    };
    27 
    28             Installers.Add(serviceInstaller);
    29             Installers.Add(processInstaller);
    30         }
    31     }

          3.用一个控制台程序生成exe文件

         

     1     static class Program
     2     {
     3         /// <summary>
     4         /// 应用程序的主入口点。
     5         /// </summary>
     6         static void Main()
     7         {
     8             var servicesToRun = new ServiceBase[]
     9                                               {
    10                                                   new TestService()
    11                                               };
    12             ServiceBase.Run(servicesToRun);
    13         }
    14     }

        接下来,编译,生成一个test.exe文件。

        然后通过vs的命令提示行,使用命令 installutil test.exe

    嘿嘿,看一下,系统服务中已经多了一个名为:“这里是显示在系统服务中的名称”的服务了

  • 相关阅读:
    JS字符串去重
    svn回退到某一版本
    WebStorm格式化代码4个空格设置
    DevExpress中 的DataGrid每一行根据其类型显示控件的种类
    各大系统刷新DNS缓存方法
    Kali Linux中前十名的Wifi攻击工具
    CentOS远程执行漏洞
    判断是否移动端的几种方法
    笔记
    Linux常用命令
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/2125793.html
Copyright © 2011-2022 走看看