2013-06-26 67 views
0

正確的方法我已經安裝使用installutil service1.exe調試窗口服務

Windows服務當我點擊Debug,我得到錯誤信息Windows Service Start Failure: Cannot start service from the command line or a debugger...。因此,我嘗試從調試菜單中附加到進程 - > Service1。但是,當我點擊Attach to Process時,它會自動進入Debug mode and does not respond to any of my break points

我在這裏錯過了什麼?

+0

http://stackoverflow.com/questions/125964/easier-way-to-start-debugging-a -windows-service-in-c-sharp –

回答

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服務項目調試選項。

終於在Program.cs將它添加到Main

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

從我的博客文章An easier way to debug windows services

+0

我加了方法。並用「-console」更新了我的調試配置。但是,當我嘗試通過按F5進行調試時,仍然收到相同的錯誤 – user544079

+0

您將其添加到錯誤的文本框中。檢查博客文章的屏幕截圖。 – jgauffin