调试Windows服务的正确方法

时间:2013-06-26 14:22:47

标签: .net windows-services

我已使用installutil service1.exe

安装了Windows服务

点击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

我在这里错过了什么步骤?

1 个答案:

答案 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;

来自我的博文An easier way to debug windows services