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

能否用VB.NET构建.NET Core 8 Windows服务?旧服务升级咨询

将VB.NET .NET 4.7 Windows服务升级到.NET Core 8.0

完全可行,.NET Core 3.0及后续版本(包括8.0)支持VB.NET开发Windows服务,只是官方默认仅提供C#模板,需手动配置项目结构。以下是具体实现步骤和示例:

一、创建基础项目

  1. 新建VB.NET 控制台应用(目标框架选.NET 8.0),Windows服务本质是托管后台逻辑的控制台程序。
  2. 安装NuGet包:Microsoft.Extensions.Hosting.WindowsServices,该包提供Windows服务的托管支持。

二、核心代码示例

1. 实现后台服务逻辑类

创建继承自BackgroundService的类,承载原服务的业务逻辑:

Imports Microsoft.Extensions.Hosting
Imports Microsoft.Extensions.Logging

Public Class VbWindowsService
    Inherits BackgroundService
    Private ReadOnly _logger As ILogger(Of VbWindowsService)

    Public Sub New(logger As ILogger(Of VbWindowsService))
        _logger = logger
    End Sub

    Protected Overrides Async Function ExecuteAsync(stoppingToken As CancellationToken) As Task
        _logger.LogInformation("VB.NET Windows服务已启动")
        Try
            While Not stoppingToken.IsCancellationRequested
                ' 替换为原服务的业务逻辑
                _logger.LogInformation("服务运行中... 当前时间:{Time}", DateTimeOffset.Now)
                Await Task.Delay(5000, stoppingToken)
            End While
        Catch ex As OperationCanceledException
            _logger.LogInformation("服务已停止")
        End Try
    End Function
End Class

2. 配置宿主并注册服务

修改Program.vb,配置服务宿主并启用Windows服务托管:

Imports Microsoft.Extensions.DependencyInjection
Imports Microsoft.Extensions.Hosting

Module Program
    Sub Main(args As String())
        Dim hostBuilder = Host.CreateDefaultBuilder(args)
            .ConfigureServices(Sub(services)
                                   ' 注册后台服务
                                   services.AddHostedService(Of VbWindowsService)()
                               End Sub)
            .UseWindowsService(Sub(options)
                                   ' 设置服务显示名称
                                   options.ServiceName = "VB8_Windows_Service"
                               End Sub)

        ' 启动服务
        hostBuilder.Build().Run()
    End Sub
End Module

三、迁移原服务逻辑

  • 将原.NET 4.7服务中OnStart、OnStop的逻辑,迁移到ExecuteAsync方法中,注意适配异步编程模式。
  • 替换旧API:原System.ServiceProcess相关API,改用Microsoft.Extensions.Hosting.WindowsServices提供的能力。
  • 配置迁移:原App.config中的配置可迁移到appsettings.json,或通过ConfigurationBuilder读取原有配置文件。

四、调试与部署

  • 调试:直接运行控制台程序即可调试服务逻辑,无需提前安装为Windows服务。
  • 部署:用dotnet publish生成发布包后,通过命令行安装服务:sc create VB8_Windows_Service binPath= "生成的EXE文件路径"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 22:29:57