Running a C# console application as a Windows service

旧巷老猫 提交于 2019-12-04 04:45:32

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.

Sani Singh Huttunen

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.

Allen Fu

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!