Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I call Close() on ServiceController?

Tags:

c#

.net

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?

like image 989
Steven S. Avatar asked Dec 09 '22 17:12

Steven S.


1 Answers

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();
  }
}
like image 134
Jehof Avatar answered Dec 11 '22 09:12

Jehof