运行一个C#控制台应用程序作为Windows服务

问题描述:

我有一个基本的C#控制台应用程序,我想作为Windows服务运行。

I have a basic C# console application that I would like to run as a Windows Service.

我已经创建的Windows服务中使用 SC创建。这工作得很好,我可以看到我在服务SERVICES.MSC 。当我尝试启动这个服务,我得到了以下错误:

I have created the Windows service using sc create. This worked fine, and I can see my service under services.msc. When I try and start this service I get the following error:

无法在本地计算机上的项目服务。错误1053:服务没有启动或控制请求,及时响应fashion.`

Could not start the PROJECT service on Local Computer. Error 1053: The service did not respond to the start or control request in a timely fashion.`

我看,这可能是由于服务code时间超过30000 毫秒执行。所以我删除了大部分的code,使正在执行几乎没有什么..但同样的错误仍然存​​在。

I read that this might be due to the service code taking longer than 30000 ms to execute. Therefore I removed the bulk of the code so that hardly anything is being executed.. yet the same error persists.

我使用.NET 3.5为这个项目。

I am using .NET 3.5 for this project.

什么原因呢?

您不能只是采取任何控制台应用程序并运行为Windows服务。首先,你需要实现将继承 ServiceBase的服务类,然后在入口点(),您需要运行具有 ServiceBase.Run服务(新YourService())。在服务类,你需要定义会发生什么时,服务的开始和结束。

You cannot just take any console application and run as Windows service. First you need to implement your service class that would inherit from ServiceBase, then in entry point (Main) you need to run the service with ServiceBase.Run(new YourService()). In your service class you need to define what happens when service starts and ends.

在理想情况下,你应该添加的ServiceInstaller到您的程序集了。您将通过这种方式能够preSET您的服务属性,并使用installutil.exe安装服务。

Ideally you should add ServiceInstaller to your assembly too. This way you will be able to preset your service properties, and use installutil.exe to install the service.