Is there any way to write code in C# that starts win service, and if that service suddenly break to write something in event log? Some try catch block?
Windows service in C#
Collapse
X
-
Tags: None
-
-
I take it that you want to start a service from an existing application rather than create your own. You can use this example as a jumping off point to start the service by name.
Now remember you'll need to know the actual service name to make this work. As far as checking the status of the service you can do this a couple of different ways. I had the following in my archive from the MSDN Social site (written by Derik Palacino). This should allow you to check if your service is running then you could go from there.Code:public static void StartService(string serviceName, int timeoutMilliseconds) { ServiceController service = new ServiceController(serviceName); try { TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); } catch { // ... } }
Code:private bool EnsureRunningService(string machineName, string serviceName, string[] args) { bool retVal = false; if (string.IsNullOrEmpty(serviceName)) throw new ArgumentException("Param cannot be null or empty!", "serviceName"); string machineInternal = string.IsNullOrEmpty(machineName) ? Environment.MachineName : machineName; ServiceController[] controllers = ServiceController.GetServices(machineInternal); List<ServiceController> svcControllers = (from controller in controllers where controller.ServiceName == serviceName select controller).ToList(); if (svcControllers.Count == 0) throw new InvalidOperationException("The service does not exist!"); else { ServiceController primary = svcControllers[0]; if (primary.Status != ServiceControllerStatus.Running) primary.Start(args); retVal = true; } return retVal; }Comment
-
No, I have made application that generates Win Service and starts it. That service is been used for a while (for couple of days for example) and then breaks. My question was if I could do everything the same way,and only add writing to log when service stops working.Comment
-
-
First of all thanks for your trying :) That's something I need if OnStop() function will be executed if service breaks. But I'm not sure that's the case. Thanks again :)Comment
Comment