0

我已经使用安装了 Windows 服务installutil service1.exe

当我单击Debug时,我收到错误消息Windows Service Start Failure: Cannot start service from the command line or a debugger...。因此,我尝试了 Debug 菜单中的 Attach to Process -> Service1。但是,当我单击 时Attach to Process,它会自动进入Debug mode and does not respond to any of my break points.

我在这里缺少什么步骤?

4

1 回答 1

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 服务项目的调试选项。

最后将其添加MainProgram.cs

 // just include this check, "Service1" is the name of your service class.
    if (WindowsServiceHelper.RunAsConsoleIfRequested<Service1>())
        return;

来自我的博客文章调试 Windows 服务的更简单方法

于 2013-06-26T14:34:15.740 回答