我目前正在编写一些Bootstrap代码,用于在控制台中运行的服务。基本上就是调用OnStart()方法,而不是使用ServiceBase启动和停止服务(因为如果未将其安装为服务,则无法运行应用程序,这使得调试变得非常困难)。
现在我正在使用Debugger.IsAttached来确定是否应该使用ServiceBase.Run或[service].OnStart,但我知道那不是最好的想法,因为有时最终用户希望在控制台中运行服务(以实时查看输出等)。
有什么想法可以确定Windows服务控制器是否启动了“我”,还是用户在控制台中启动了“我”?显然Environment.IsUserInteractive不是答案。我考虑过使用命令行参数,但那似乎很“糟糕”。
我总是可以尝试在ServiceBase.Run周围使用try-catch语句,但那似乎也很“糟糕”。编辑:try-catch无效。
我有一个解决方案:在此处公布给其他感兴趣的人:
public void Run()
{
if (Debugger.IsAttached || Environment.GetCommandLineArgs().Contains<string>("-console"))
{
RunAllServices();
}
else
{
try
{
string temp = Console.Title;
ServiceBase.Run((ServiceBase[])ComponentsToRun);
}
catch
{
RunAllServices();
}
}
} // void Run
private void RunAllServices()
{
foreach (ConsoleService component in ComponentsToRun)
{
component.Start();
}
WaitForCTRLC();
foreach (ConsoleService component in ComponentsToRun)
{
component.Stop();
}
}
编辑:StackOverflow上还有一个问题,其中一位使用者遇到了Environment.CurrentDirectory为"C:\Windows\System32" 的问题,看起来这可能是答案。我今天会进行测试。