• 使用.NET Core创建Windows服务详细步骤



    #创建步骤

    使用该方式创建,首先要确保你已经安装了.NET Core 3.0或以上版本 . 但是如果你想要在.NET Core 2.x项目中使用这个方式,应该是行不通的。

    1、使用Visual Studio创建

    打开Visual Studio,创建新项目,找到Worker Service模板。
    在这里插入图片描述

    2、使用命令行创建

    dotnet new worker
    

    #项目结构说明

    创建出来的项目,包含两个主要文件。其中Program.cs文件是应用的启动“引导程序”。另外一个文件是worker.cs文件,在这个文件中,你可以编写你的服务逻辑。同时在依赖项的包中引入了Microsoft.Extensions.Hosting包。
    在这里插入图片描述

    #将应用转换成Window服务

    当前项目可在linux下完美运行,但是还不能以服务的方式在windows上安装运行。

    1、引入Microsoft.Extensions.Hosting.WindowsServices

    为了将应用转换成Windows服务,我们需要使用如下命令引入一个包。

    Install-Package Microsoft.Extensions.Hosting.WindowsServices
    

    在这里插入图片描述

    2、修改代码

    需要修改Program.cs文件,添加UseWindowsService()方法的调用。

        public class Program
        {
            public static void Main(string[] args)
            {
                CreateHostBuilder(args).Build().Run();
            }
    
            public static IHostBuilder CreateHostBuilder(string[] args)
            {
                var host = Host.CreateDefaultBuilder(args);
                //判断当前系统是否为windows
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    host.UseWindowsService();
                }
                return host.ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                });
            }
        }
    

    代码中增加了对操作系统的判断,从而可以兼容windows和linux。

    3、发布

    使用Visual Studio发布:
    在这里插入图片描述
    使用命令行发布:

    dotnet publish -r win-x64 -c Release
    

    4、使用SC命令在windows上安装服务

    sc create TestService BinPath=D:dirWindowsServiceExample.exe
    

    也可以创建一个bat文件,用来安装windows服务,如下:

    @echo off 
    @title 安装windows服务
    @echo off 
    echo= 安装服务!
    @echo off  
    @sc create worktest binPath= "%~dp0WorkerService1.exe"  
    echo= 启动服务!
    @echo off  
    @sc start worktest 
    @echo off  
    echo= 配置服务! 
    @echo off  
    @sc config worktest start= AUTO  
    @echo off  
    echo= 成功安装、启动、配置服务!   
    @pause
    

    将bat文件放到服务文件同目录,修改下服务名和exe名字即可双击运行安装。

    SC其他操作服务的常用命令:

    sc start TestService
    sc stop TestService
    sc delete TestService
    

  • 相关阅读:
    C#
    if
    .net 5.0
    C# 未提供必须形参对应的实参
    EasyRTC报错 “[ERR] mod_local_stream.c:880 Unknown source default”排查
    EasyRTC通过公网进入会议室失败问题排查及解决
    【CF1558B】Up the Strip
    【AT Keyence2019E】Connecting Cities
    【洛谷P7470】岛屿探险
    【洛谷P6628】丁香之路
  • 原文地址:https://www.cnblogs.com/willingtolove/p/13863945.html
Copyright © 2020-2023  润新知