.NET控制台应用程序中防止程序立即退出

发布于:2025-07-16 ⋅ 阅读:(15) ⋅ 点赞:(0)

在VB.NET控制台应用程序中防止程序立即退出,主要有以下几种常用方法,根据需求选择适合的方案:

方法1:等待用户输入(推荐)

Module Module1
    Sub Main()
        Console.WriteLine("程序开始运行...")
        
        ' 这里是你的主程序逻辑
        DoWork()
        
        Console.WriteLine("按任意键退出程序...")
        Console.ReadKey() ' 等待用户按键
    End Sub
    
    Sub DoWork()
        ' 你的业务逻辑代码
        Console.WriteLine("正在执行任务...")
    End Sub
End Module
### 方法2:无限循环(适用于后台服务)
Dim running As Boolean = True

Sub Main()
    Console.CancelKeyPress += Sub(sender, e)
        e.Cancel = True ' 防止Ctrl+C直接终止
        running = False
    End Sub

    While running
        ' 主循环逻辑
        Console.WriteLine($"{DateTime.Now}: 执行中...")
        Threading.Thread.Sleep(1000) ' 每秒执行一次
    End While
    
    Console.WriteLine("程序正常退出")
End Sub

方法3:使用消息循环(适合GUI集成)

' 需要添加对System.Windows.Forms的引用
Sub Main()
    Console.WriteLine("服务已启动")
    
    Application.Run() ' 创建Windows消息循环
    
    ' 在需要退出的地方调用 Application.Exit()
End Sub

方法4:自定义退出条件

Sub Main()
    Dim exitCode As Integer = 0
    
    Do
        Try
            ' 执行主要逻辑
            ProcessData()
        Catch ex As Exception
            exitCode = 1
            running = False
        End Try
        
        Threading.Thread.Sleep(500) ' 避免CPU占用过高
    Loop While running
    
    Environment.Exit(exitCode)
End Sub

高级方案:转换为Windows服务

' 需要安装 NuGet 包: Microsoft.Extensions.Hosting.WindowsServices
Imports Microsoft.Extensions.Hosting

Module Program
    Sub Main(args As String())
        CreateHostBuilder(args).Build().Run()
    End Sub

    Public Function CreateHostBuilder(args As String()) As IHostBuilder
        Return Host.CreateDefaultBuilder(args)
            .UseWindowsService() ' 启用Windows服务支持
            .ConfigureServices(Sub(services)
                services.AddHostedService(Of WorkerService)()
            End Sub)
    End Function
End Module

Public Class WorkerService
    Inherits BackgroundService

    Protected Overrides Async Function ExecuteAsync(stoppingToken As CancellationToken) As Task
        While Not stoppingToken.IsCancellationRequested
            ' 持续执行的后台任务
            Await Task.Delay(1000, stoppingToken)
        End While
    End Function
End Class

调试技巧:

  1. 防止Visual Studio调试时退出
   Sub Main()
       If Debugger.IsAttached Then
           Console.WriteLine("调试模式 - 按任意键退出")
           Console.ReadKey()
       End If
   End Sub
  1. 作为服务安装(使用SC命令):
    sc create MyService binPath="C:\Path\To\YourApp.exe"
    sc start MyService
    

选择方案的建议:

  • 临时调试:使用 Console.ReadKey()
  • 后台服务:使用无限循环或转换为Windows服务
  • 生产环境:推荐Windows服务方案(方法4)

注意:长期运行的程序需要添加适当的异常处理,避免因未处理异常导致意外退出。


网站公告

今日签到

点亮在社区的每一天
去签到