在 Windows 服务运行之前,必须首先使用 installutil 进行 "安装"。例如:
C:\installutil -i c:\path\to\project\debug\service.exe
你可以打开服务列表来启动它。例如:
一旦它已经启动,你可以进入Visual Studio,点击“调试”,然后点击“附加到进程”。
另一种技术是在服务的OnStart()方法中添加这行代码:
System.Diagnostics.Debugger.Launch();
当你这样做时,它会提示你选择一个Visual Studio实例来调试服务。
OnCommitted
方法中使用以下代码创建安装程序非常好用:using (ServiceController sc = new ServiceController(__SERVICENAME__)){sc.Start();}
(或者您可以按照描述手动启动)。 - Brad ChristieC:\InstallUtil.exe
。你应该查看C:\Windows\Microsoft.NET\Framework[ARCH]\v[VERSION]\InstallUtil.exe
。这里会有更多的可能性找到它。请注意替换[ARCH]
和[VERSION]
为适当的架构和版本号。 - AlicanC您可以根据当前处于DEBUG模式(通常在Visual Studio内但不一定)还是RELEASE模式(在生产环境中作为服务运行)来更改程序集的启动模式:
更改如下内容:
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(ServicesToRun);
}
}
对此:static class Program
{
static void Main()
{
#if(!DEBUG)
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(ServicesToRun);
#else
MyService myServ = new MyService();
myServ.Process();
// here Process is my Service function
// that will run when my service onstart is call
// you need to call your own method or function name here instead of Process();
#endif
}
}
这项技术来源于该文章,文章作者是Tejas Vaishnav。我在此处复制代码片段,因为SO更喜欢完整的答案,而不是可能会消失的链接。
Environment.UserInteractive
标记。如果设置了该标记,则可以将服务运行时输出到控制台,而不是让它运行到返回该错误的ServiceBase代码。 if (Environment.UserInteractive)
{
var service = new WindowsService();
service.TestInConsole(args);
return;
}
由于您的服务中的OnStart和OnStop方法是protected
的,因此您需要在该类中添加另一个方法,您可以从Main()运行该方法,并为您调用这些方法,例如:
public void TestInConsole(string[] args)
{
Console.WriteLine($"Service starting...");
this.OnStart(args);
Console.WriteLine($"Service started. Press any key to stop.");
Console.ReadKey();
Console.WriteLine($"Service stopping...");
this.OnStop();
Console.WriteLine($"Service stopped. Closing in 5 seconds.");
System.Threading.Thread.Sleep(5000);
}
install-package WindowsService.Gui
using System.ServiceProcess;
using ServiceProcess.Helpers; //HERE
namespace DemoService
{
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
//ServiceBase.Run(ServicesToRun);
ServicesToRun.LoadServices(); //AND HERE
}
}
}
声明:我是该项目的维护者
注意:UI为可选项