简体   繁体   中英

Running a C# console application as a Windows service

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?

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.

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM