Running a C# console application as a Windows serv

2019-04-07 12:12发布

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

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:

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.`

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.

I am using .NET 3.5 for this project.

What would cause this?

6条回答
▲ chillily
2楼-- · 2019-04-07 12:44

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.

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.

查看更多
男人必须洒脱
3楼-- · 2019-04-07 12:52

I have had great success with TopShelf. This is a nuget package that allows your .NET console app to also have the necessary Windows Service hooks such that it can happily run as either a console app (useful for debugging), or be installed as a Windows Service.

查看更多
干净又极端
4楼-- · 2019-04-07 13:03
相关推荐>>
5楼-- · 2019-04-07 13:03

why is this so? – wulfgar.pro Jun 3 '11 at 1:13

@WulfgarPro - because windows service application has a little different architecture. You need to define what to do when service starts and ends. – Alex Aza Jun 3 '11 at 1:15

(Unfortunately I can't write a comment yet.) It is because SCM (Service Control Manager) controls the service trough ServiceBase Class. If one would only need to define what it does when it starts and stops there would be no need for inheritance and overriding. One could simply create those two methods. Unfortunately there is a bit more work involved because ServiceBase contains a bit more functionality.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-04-07 13:04

I do not know what "sc create" is. But I know, using Visual Studio 2010, one can build a Windows service project. By the way, I have created a project of this kind and it does work well all the way.

查看更多
ゆ 、 Hurt°
7楼-- · 2019-04-07 13:07

Not any old application can be run as a service, especially under more recent versions of Windows. They are expected to support certain functionality, respond to certain requests, and (again, under recent versions of Windows) not interact with the user directly.

If you want a service, write an application specifically designed to be a service.

查看更多
登录 后发表回答