Currently I have a method like this:
private bool IsMyServiceRunning(string serviceName)
{
if (String.IsNullOrEmpty(serviceName))
throw new InvalidOperationException("ServiceName cannot be null or empty");
using (var service = new ServiceController(serviceName))
{
if (service.Status == ServiceControllerStatus.Running)
return true;
else
return false;
}
}
Is this the right way to use the ServiceController class?
The reason I ask is that all the examples I have seen do not call the Close() method when they're done using it. Are those bad examples or am I missing something?
You are using the ServiceController
with a using
-statement. This will call Dispose
on the ServiceController which is the same as calling Close() explicitly .
So in your case there is no need to call Close again.
Without the using-statement, it is necessary to call Close() or Dispose() on the ServiceController, cause it uses unmanaged resources that need to be released. Otherwise you have a memory leak.
ServiceController service = null;
try {
service = new ServiceController(serviceName);
if (service.Status == ServiceControllerStatus.Running) {
return true;
}
else {
return false;
}
}
finally{
if (service != null) {
service.Close(); // or service.Dispose();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With