.NET控制台应用程序中防止程序立即退出
在VB.NET控制台应用程序中防止程序立即退出,主要有以下几种常用方法,根据需求选择适合的方案:
方法1:等待用户输入(推荐)
Module Module1Sub Main()Console.WriteLine("程序开始运行...")' 这里是你的主程序逻辑DoWork()Console.WriteLine("按任意键退出程序...")Console.ReadKey() ' 等待用户按键End SubSub DoWork()' 你的业务逻辑代码Console.WriteLine("正在执行任务...")End Sub
End Module
### 方法2:无限循环(适用于后台服务)
Dim running As Boolean = TrueSub Main()Console.CancelKeyPress += Sub(sender, e)e.Cancel = True ' 防止Ctrl+C直接终止running = FalseEnd SubWhile running' 主循环逻辑Console.WriteLine($"{DateTime.Now}: 执行中...")Threading.Thread.Sleep(1000) ' 每秒执行一次End WhileConsole.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 = 0DoTry' 执行主要逻辑ProcessData()Catch ex As ExceptionexitCode = 1running = FalseEnd TryThreading.Thread.Sleep(500) ' 避免CPU占用过高Loop While runningEnvironment.Exit(exitCode)
End Sub
高级方案:转换为Windows服务
' 需要安装 NuGet 包: Microsoft.Extensions.Hosting.WindowsServices
Imports Microsoft.Extensions.HostingModule ProgramSub Main(args As String())CreateHostBuilder(args).Build().Run()End SubPublic Function CreateHostBuilder(args As String()) As IHostBuilderReturn Host.CreateDefaultBuilder(args).UseWindowsService() ' 启用Windows服务支持.ConfigureServices(Sub(services)services.AddHostedService(Of WorkerService)()End Sub)End Function
End ModulePublic Class WorkerServiceInherits BackgroundServiceProtected Overrides Async Function ExecuteAsync(stoppingToken As CancellationToken) As TaskWhile Not stoppingToken.IsCancellationRequested' 持续执行的后台任务Await Task.Delay(1000, stoppingToken)End WhileEnd Function
End Class
调试技巧:
- 防止Visual Studio调试时退出:
Sub Main()If Debugger.IsAttached ThenConsole.WriteLine("调试模式 - 按任意键退出")Console.ReadKey()End IfEnd Sub
- 作为服务安装(使用SC命令):
sc create MyService binPath="C:\Path\To\YourApp.exe" sc start MyService
选择方案的建议:
- 临时调试:使用
Console.ReadKey()
- 后台服务:使用无限循环或转换为Windows服务
- 生产环境:推荐Windows服务方案(方法4)
注意:长期运行的程序需要添加适当的异常处理,避免因未处理异常导致意外退出。