Windows服务程序开发


新建Windows服务 项目

填写 项目名称 位置 ,和 framework版本 
点击 创建   获得项目目录结构
 

配置服务

双击Service1.cs,在设计器中右键 选择 添加安装程序  
 
然后得到一个ProjectInstaller.cs文件
 
在ProjectInstaller.cs设计界面,按下F7,或者右键选择查看代码
  1. 设置服务运行所使用的账户类型 
    this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService;
  2. 设置服务的名称,显示名称和服务描述 
    // 设定服务名称
    this.serviceInstaller1.ServiceName = System.Configuration.ConfigurationManager.AppSettings["ServiceName"];
    this.serviceInstaller1.DisplayName = System.Configuration.ConfigurationManager.AppSettings["DisplayName"];
    
    // 服务描述
    this.serviceInstaller1.Description = System.Configuration.ConfigurationManager.AppSettings["Description"];

     

    注意:这里是从app.config中获取参数  

    App.Config 配置为:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <appSettings>
        <add key="ServiceName" value="GZProxyServer"/>
        <add key="DisplayName" value="GZProxyServer在线代理服务"/>
        <add key="Description" value="支持HTTP代理"/>
      </appSettings>
    </configuration>
  3. 设置服务的启动方式,自启动  
    // 设定服务的启动方式 自动启动
    this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
    // 延时启动
    this.serviceInstaller1.DelayedAutoStart = true;
 
 
为项目添加引用 System.Configuration 
 

实现服务要执行的内容

修改 Service1.cs的代码
public partial class Service1 : ServiceBase
{
    public Service1()
    {
        InitializeComponent();
    }
    /// <summary>
    /// 服务启动
    /// </summary>
    /// <param name="args"></param>
    protected override void OnStart(string[] args)
    {
        string IP = System.Configuration.ConfigurationManager.AppSettings["ListeningIPInterface"];
        int Port = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ListeningPort"]);
        string CertFile = System.Configuration.ConfigurationManager.AppSettings["CertificateFile"];
        ProxyServer.Server.Start(IP, Port, CertFile);
    }
    /// <summary>
    /// 服务停止
    /// </summary>
    protected override void OnStop()
    {
        ProxyServer.Server.Stop();
    }
}
GarsonZhang www.yesdotnet.com

 

 

版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
YES开发框架
上一篇:新建vue项目出现error Unexpected ‘debugger‘ statement no-debugger
下一篇:C#解析指定dll的app.config配置文件
评论列表

发表评论

评论内容
昵称:
关联文章

Windows服务程序开发
VS调试 Windows 服务应用程序
VS制作C#程序windows安装程序
Python Windows服务
删除 windows 服务
vs2019+windows服务+nancy+打包
Python windows服务报错: 1063 StartServiceCtrlDispatcher 服务进程无法连接到服务控制器上
服务安装失败:未能加载文件或程序
GZUpdate自动升级服务 .NET C/S Winform客户端程序自动升级演示
Python windows服务报错: 1053:服务没有及时响应启动或控制请求
windows平台的分布式微服务解决方案(5)--Web服务/WebApi的负载均衡
EFCore数据库提供程序
使用.NET 6开发TodoList应用(28)——实现应用程序健康检查
.NET中大型项目开发必备(5)--Web服务/WebApi的负载均衡
windows Redis配置
程序测试
Python windows服务报错: Installing service ALicense Error installing service: 拒绝访问
windows平台的分布式微服务解决方案(2)--跨域访问
windows平台的分布式微服务解决方案(6)--IUtility工具介绍
Python暂停程序执行

联系我们
联系电话:15090125178(微信同号)
电子邮箱:garson_zhang@163.com
站长微信二维码
微信二维码