目前,在开发 Windows 服务时,我修改 csproj 以在 Debug模式下将 OutputType 设置为 Exe,以便获得控制台窗口,并且可以轻松调试服务。
我很好奇的是,像这样在 Release模式下投入生产有什么问题吗?我没有看到控制台窗口,当通过 InstallUtil 安装服务然后启动时,它似乎没有显示或隐藏或没有创建。
有什么想法吗?
最佳答案
大多数服务通常是 exe 输出类型。是的,当它作为服务运行时,不会有控制台,但只要您不从控制台读取任何内容,就不应该成为问题。您可以将控制台作为服务写入,系统将忽略该文本。
通常我所做的是让程序监视作为命令行参数传入的字符串 --debug
,如果是,则将服务作为控制台应用程序启动,如果不是将其作为服务启动。以下是如何执行此操作的示例:
static void Main(string[] args)
{
var debugMode = args.Contains("--debug", StringComparer.InvariantCultureIgnoreCase);
if (!debugMode)
{
ServiceBase[] servicesToRun =
{
new MyService();
};
ServiceBase.Run(servicesToRun);
}
else
{
var service = new MyService();
service.StartService(args);
Console.WriteLine("Service is now running, press enter to stop...");
Console.ReadLine();
service.StopService();
}
}
}
然后在我做的服务代码中
public partial class MyService : ServiceBase
{
internal void StartService(string[] args)
{
OnStart(args);
}
internal void StopService()
{
OnStop();
}
//... The rest of the code here
}
关于c# - 编译输出类型为 Exe 的 Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37752449/