You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Studio 2019中找不到Windows Service模板,如何创建Windows服务?

Visual Studio 2019创建Windows服务的解决方案

一、解决找不到Windows Service模板的问题

VS2019默认未预装Windows服务相关模板,需手动安装组件:

  • 打开Visual Studio Installer,点击「修改」
  • 在「工作负载」标签下,勾选「.NET桌面开发」(若已勾选,直接看下一步)
  • 切换到「单个组件」,搜索「Windows Service模板」,勾选「Windows Service (.NET Framework)」组件
  • 点击「修改」完成安装,重启Visual Studio

二、创建Windows服务的两种方式

方式1:使用官方模板创建

组件安装完成后,重新打开VS:

  • 选择「新建项目」,搜索「Windows Service (.NET Framework)」
  • 填写项目名称与路径,点击「创建」
  • 生成的项目包含Service1.cs,可重命名该文件,并重写OnStart和OnStop方法编写服务逻辑

方式2:将控制台应用转为Windows服务

完全可以把控制台应用改造为Windows服务,步骤如下:

  1. 创建一个.NET Framework控制台应用(.NET Core/.NET 5+也支持,配置略有不同)
  2. 右键项目→「管理NuGet程序包」,安装System.ServiceProcess包
  3. 添加继承自ServiceBase的服务类:
using System.ServiceProcess;

namespace ConsoleToServiceDemo
{
    public class MyCustomService : ServiceBase
    {
        protected override void OnStart(string[] args)
        {
            // 编写服务启动逻辑,可调用原控制台的业务代码
        }

        protected override void OnStop()
        {
            // 编写服务停止逻辑
        }
    }
}
  1. 修改Program.cs的Main方法,支持控制台调试与服务运行两种模式:
using System;
using System.ServiceProcess;

namespace ConsoleToServiceDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            if (Environment.UserInteractive)
            {
                // 控制台调试模式,直接执行服务逻辑
                var service = new MyCustomService();
                service.OnStart(args);
                Console.WriteLine("服务已启动,按任意键停止...");
                Console.ReadKey();
                service.OnStop();
            }
            else
            {
                // 以Windows服务模式运行
                ServiceBase.Run(new MyCustomService());
            }
        }
    }
}
  1. 添加服务安装程序:右键服务类文件→「添加安装程序」,自动生成ProjectInstaller.cs
    • 选中serviceProcessInstaller1,在属性窗口设置Account为LocalSystem
    • 选中serviceInstaller1,设置ServiceName(服务显示名称)、StartType(如Automatic设为自动启动)
  2. 编译项目后,通过命令行安装服务:
    • 打开管理员命令提示符,进入项目输出目录(如bin\Release)
    • 安装命令:installutil.exe ConsoleToServiceDemo.exe
    • 卸载命令:installutil.exe /u ConsoleToServiceDemo.exe

三、额外说明

  • 若使用.NET Core/.NET 5+开发,无需安装System.ServiceProcess,可通过Microsoft.Extensions.Hosting.WindowsServices包,借助HostBuilder快速配置服务
  • 调试阶段优先用控制台模式运行,验证逻辑无误后再安装为Windows服务

内容的提问来源于stack exchange,提问作者Akshay Malvankar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 16:01:14