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

基于Windows兼容性包创建.NET Core 2.0 Windows服务的方法咨询

在.NET Core 2.0中创建Windows服务的完整指南

我之前也遇到过类似的情况——习惯了.NET Framework的服务向导,刚转到.NET Core 2.0时确实有点懵。不过别担心,结合Windows兼容性包(WCP),我们完全可以一步步搭建起可用的Windows服务,下面是具体步骤:

1. 先创建基础控制台项目

.NET Core 2.0没有专门的Windows服务模板,所以我们从控制台项目入手:

  • 如果用Visual Studio:新建项目 → 选择「.NET Core」下的「控制台应用(.NET Core)」
  • 如果用命令行:执行 dotnet new console -n MyWindowsService

2. 确认Windows兼容性包已正确安装

你提到已经装了NuGet包,还是建议检查一下项目文件(.csproj)里是否有这个引用,确保版本匹配.NET Core 2.0:

<PackageReference Include="Microsoft.Windows.Compatibility" Version="2.0.0" />

如果没装的话,用NuGet包管理器搜索「Microsoft.Windows.Compatibility」安装对应版本即可。

3. 编写服务核心代码

接下来我们要继承System.ServiceProcess.ServiceBase(这正是WCP提供的类),重写服务的启动、停止逻辑,同时处理调试和正式运行的分支:

using System;
using System.ServiceProcess;

namespace MyWindowsService
{
    public class MyCustomService : ServiceBase
    {
        public MyCustomService()
        {
            // 配置服务名称和事件日志源(方便排查问题)
            ServiceName = "MyCustomService";
            EventLog.Source = "MyCustomServiceSource";
            EventLog.Log = "Application";

            // 如果事件源不存在,创建它
            if (!EventLog.SourceExists(EventLog.Source))
            {
                EventLog.CreateEventSource(EventLog.Source, EventLog.Log);
            }
        }

        protected override void OnStart(string[] args)
        {
            // 这里写服务启动后的业务逻辑
            // 比如启动后台定时任务、监听消息队列等
            EventLog.WriteEntry("MyCustomService 已成功启动", EventLogEntryType.Information);
        }

        protected override void OnStop()
        {
            // 这里写服务停止时的清理逻辑
            // 比如释放资源、停止后台线程、保存状态等
            EventLog.WriteEntry("MyCustomService 已停止", EventLogEntryType.Information);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // 判断是否处于调试模式:调试时直接运行服务逻辑,不用安装
            if (System.Diagnostics.Debugger.IsAttached)
            {
                var service = new MyCustomService();
                service.OnStart(args);
                Console.WriteLine("服务已启动,按任意键停止调试...");
                Console.ReadKey();
                service.OnStop();
            }
            else
            {
                // 正式运行时,通过ServiceBase启动服务
                ServiceBase.Run(new MyCustomService());
            }
        }
    }
}

4. 配置项目以适配Windows服务

修改你的.csproj文件,添加<WindowsExe>true</WindowsExe>,这样发布后的程序不会弹出控制台窗口:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <!-- 关键配置:标记为Windows应用,隐藏控制台窗口 -->
    <WindowsExe>true</WindowsExe>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Windows.Compatibility" Version="2.0.0" />
  </ItemGroup>
</Project>

5. 发布服务

用命令行执行发布命令(根据你的需求选择目标平台,这里以x64为例):

dotnet publish -c Release -r win-x64

发布完成后,可执行文件会在bin/Release/netcoreapp2.0/win-x64/publish目录下。

6. 安装和管理服务

使用Windows自带的sc命令来管理服务(需要以管理员身份打开命令提示符):

  • 安装服务:注意binPath=后面必须加空格,路径要换成你自己的发布路径
    sc create MyCustomService binPath= "C:\Projects\MyWindowsService\bin\Release\netcoreapp2.0\win-x64\publish\MyWindowsService.exe"
    
  • 启动服务:
    sc start MyCustomService
    
  • 停止服务:
    sc stop MyCustomService
    
  • 删除服务(如果需要卸载):
    sc delete MyCustomService
    

调试小技巧

在Visual Studio中直接运行项目时,因为代码里判断了Debugger.IsAttached,会进入调试模式——你可以直接在OnStart、OnStop方法里打断点,不用安装服务就能测试逻辑,非常方便。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:36:10