我在VS中创建了一个Windows服务:文件->新建项目->C#->Windows服务 但我不知道如何运行和测试它。VS 说我必须安装 Windows 服务才能运行它。但我只是想测试它,但不想安装它。任何人都可以帮助我吗?
最佳答案
要调试 Windows 服务,请在 Main()
中添加以下内容:
if (!Environment.UserInteractive) {
// We are not in debug mode, startup as service
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyServer() };
ServiceBase.Run(ServicesToRun);
} else {
// We are in debug mode, startup as application
MyServer service = new MyServer();
service.StartService();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
}
您的类中的以下方法 MyServer
:
public void StartService() {
this.OnStart(new string[0]);
}
现在按 F5 进行调试,就像任何 winform 或控制台应用程序一样。
关于c# - 如何在 VS 中运行和测试 Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7967218/