我已使用installutil service1.exe
点击Debug
后,收到错误消息Windows Service Start Failure: Cannot start service from the command line or a debugger...
。因此我尝试了Attach to Process - > Debug菜单中的Service1。但是,当我点击Attach to Process
时,它会自动输入Debug mode and does not respond to any of my break points
。
我在这里错过了什么步骤?
答案 0 :(得分:1)
以下更改允许您像调用任何其他控制台应用程序一样调试Windows服务。
将此课程添加到您的项目中:
public static class WindowsServiceHelper
{
[DllImport("kernel32")]
static extern bool AllocConsole();
public static bool RunAsConsoleIfRequested<T>() where T : ServiceBase, new()
{
if (!Environment.CommandLine.Contains("-console"))
return false;
var args = Environment.GetCommandLineArgs().Where(name => name != "-console").ToArray();
AllocConsole();
var service = new T();
var onstart = service.GetType().GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);
onstart.Invoke(service, new object[] {args});
Console.WriteLine("Your service named '" + service.GetType().FullName + "' is up and running.\r\nPress 'ENTER' to stop it.");
Console.ReadLine();
var onstop = service.GetType().GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);
onstop.Invoke(service, null);
return true;
}
}
然后将-console
添加到Windows服务项目的调试选项中。
最后将其添加到Main
中的Program.cs
:
// just include this check, "Service1" is the name of your service class.
if (WindowsServiceHelper.RunAsConsoleIfRequested<Service1>())
return;