c#应用服务在启动时如何适配控制台和windows服务两种应用,在program.cs应用程序主入口加入相关配置

📅 2026/7/2 7:28:13
c#应用服务在启动时如何适配控制台和windows服务两种应用,在program.cs应用程序主入口加入相关配置
c#应用服务在启动时如何适配控制台和windows服务两种应用在program.cs应用程序主入口加入相关配置即可流程创建一个windows form application 应用我这个是一个需要挂在到windows服务的应用程序用于plc读写的中间件然后项目属性的output-type可以调整成console application控制台应用输出那么可以通过判断是从哪个入口打开来执行控制台输出还是windows服务启动(非交互式的)如果到正式环境最好用windows服务来执行它是由服务管理器来管理更安全。/// summary /// 程序入口交互式/调试器下以控制台方式跑业务逻辑由 SCM 启动时走 Windows 服务。 /// /summary static class Program { /// summary /// 应用程序主入口。 /// /summary static void Main(string[] args) { if (ShouldRunAsConsole(args)) { var svc new PlcMiddlewareService(); svc.DebugStart(); Console.WriteLine(控制台/调试模式已启动日志目录: SimpleFileLogger.GetLogDirectory()); Console.WriteLine(回车退出...); Console.ReadLine(); svc.DebugStop(); return; } ServiceBase.Run(new PlcMiddlewareService()); } /// summary /// 是否在控制台/VS 下调试交互式进程、已附加调试器、或显式传入 /console。 /// 由「服务」管理器启动的进程一般为非交互式此时走 ServiceBase.Run。 /// /summary private static bool ShouldRunAsConsole(string[] args) { if (args ! null) { foreach (string a in args) { if (string.IsNullOrEmpty(a)) continue; if (string.Equals(a.Trim(), /console, StringComparison.OrdinalIgnoreCase)) return true; } } if (Debugger.IsAttached) return true; return Environment.UserInteractive; } }写好入口后如果要将应用程序的exe注册到windows服务可以用sc或者InstallUtil来注册后者要写一个安装程序类后文会提到。