zoukankan      html  css  js  c++  java
  • 使用.Net Core 2.2创建windows服务

    使用.Net Core 2.2创建windows服务

    我的环境

    • win 10 home
    • Visual Studio 2019 v16.1.3
    • 安装有.net core 2.2

    创建项目

    编辑项目文件

    在 PropertyGroup 配置节 加入属性 <RuntimeIdentifier>win-x64</RuntimeIdentifier>

    保存后,重新生成项目

    在项目文件夹下,会有文件夹 binDebug etcoreapp2.2win-x64,里面包含了exe文件。

    测试服务类的编写

    安装nuget包

    Install-Package System.ServiceProcess.ServiceController -Version 4.5.0
    

    修改启动类 Programe.cs

    using System;
    using System.IO;
    using System.ServiceProcess;
    
    namespace TestService
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (var service = new TestSevice())
                {
                    ServiceBase.Run(service);
                }
            }
        }
    
        internal class TestSevice : ServiceBase
        {
            public TestSevice()
            {
                ServiceName = "TestService";
            }
    
            protected override void OnStart(string[] args)
            {
                string filename = CheckFileExists();
                File.AppendAllText(filename, $"{DateTime.Now} started.{Environment.NewLine}");
            }
    
            protected override void OnStop()
            {
                string filename = CheckFileExists();
                File.AppendAllText(filename, $"{DateTime.Now} stopped.{Environment.NewLine}");
            }
    
            private static string CheckFileExists()
            {
                string filename = System.AppDomain.CurrentDomain.BaseDirectory + @"MyService.txt";
                if (!File.Exists(filename))
                {
                    File.Create(filename);
                }
    
                return filename;
            }
    
        }
    }
    
    

    服务安装、启动、卸载

    安装

    sc create testservice binpath=D:source eposTestConsoleServiceTestServiceinDebug etcoreapp2.2win-x64TestService.exe

    卸载

    sc delete testservice

    启动

    不能通过命令行启动服务

    sc start testservice

    只能去服务管理器使用鼠标启动服务,具体原因暂未研究

    反复启动停止,然后去exe所在目录下查看MyService.txt的内容,确认服务的启动。

    参考文档

  • 相关阅读:
    erlang转化中文为url
    erlang中检查内存泄露
    git找回当前目录下误删的所有文件
    使用rebar编译lager,deps列表,lager要放到第一位。
    Visualizing Concurrency in Go--转
    erlang init:stop()不起效
    linux设置时间
    erlang驱动使用mysql-otp
    mysql-otp 驱动中设置utf8mb4
    erlang node time ticket
  • 原文地址:https://www.cnblogs.com/xyfy/p/11024597.html
Copyright © 2011-2022 走看看