• 系统服务的最简单实现


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

          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

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

  • 相关阅读:
    sql——查询出表中不为空或为空字段的总值数
    sql语句——根据身份证号提取省份、出生日期、年龄、性别。
    1.两数之和
    Java虚拟机
    【10.18】
    议论文:是否应该留学
    议论文:阅读能力
    应用文:线上广告
    通知(重点:格式)
    书信(重点:格式)
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/2125793.html
Copyright © 2020-2023  润新知