Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a service written in .NET self-terminate?

Tags:

I have a service application written in C# and under certain circumstances, I would like it to terminate itself. This would happen after the service has been running for a while, so this would not be happening in the OnStart() event.

Everything that I have read so far suggests that the only safe way to terminate a service is through the Service Control Manager. My service runs as Local Service and does not have the rights to start or stop services, so I can't access the SCM from the service itself. Is there another way to self-terminate while still playing by the rules of the SCM?

like image 470
Chris Miller Avatar asked Feb 16 '09 19:02

Chris Miller


People also ask

Can we create Windows Service in .NET core?

NET Core and . NET 5+, developers who relied on . NET Framework could create Windows Services to perform background tasks or execute long-running processes. This functionality is still available and you can create Worker Services that run as a Windows Service.

How do I write a Windows service?

To create a Windows Service application Create a Windows Service project. For instructions on writing a service without using the template, see How to: Write Services Programmatically. In the Properties window, set the ServiceName property for your service.


2 Answers

Try ServiceBase.Stop().

like image 114
configurator Avatar answered Sep 19 '22 02:09

configurator


If you want to terminate the service instead of stopping it (perhaps because the service has caught an otherwise unhandled exception) you can use Environment.Exit(1) (use another exit code if you want).

Windows will discover that the service has terminated unexpectedly. If the service has been configured to recover the recovery procedure will be used which includes options for restarting the service, running a program or restarting the computer.

like image 28
Martin Liversage Avatar answered Sep 22 '22 02:09

Martin Liversage