c#应用服务在启动时如何适配控制台和windows服务两种应用,在program.cs应用程序主入口加入相关配置即可
流程:创建一个windows form application 应用,我这个是一个需要挂在到windows服务的应用程序,用于plc读写的中间件,然后项目属性的output-type可以调整成console application,控制台应用输出,那么可以通过判断是从哪个入口打开,来执行控制台输出还是windows服务启动(非交互式的),如果到正式环境,最好用windows服务来执行,它是由服务管理器来管理,更安全。
cs
/// <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来注册,后者要写一个安装程序类,后文会提到。