4

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?

Steven S.
  • 654
  • 6
  • 10

4 Answers4

7

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();
  }
}
Jehof
  • 32,386
  • 9
  • 115
  • 149
4

Your example wraps the ServiceController in a using statement, which will call Dispose, which will clean up the object. It is equivalent to calling Close.

shf301
  • 30,022
  • 2
  • 46
  • 83
3

Close() is not being called because the using syntactic sugar is being used here.

using (var resource = new Resource())
{
}

is equivalent to:

{
    var resource = new Resource();
    try
    {
    }
    finally
    {
        if (resource != null)
        {
            resource.Dispose();
        }
    }
}

The automatic call to Dispose() cleans up the resources.

See this blog post for more information.

Umar Farooq Khawaja
  • 3,805
  • 1
  • 28
  • 50
0

I have used the close() method again and again but i can't dispose() used again. The Dispose() have used the connection in database...

DOT.NET
  • 101
  • 14
  • 1
    I have no clue why two people up-voted this. The last sentence does not make sense, and the first sentence is *false*. You can call `Dispose()` over, and over, and over and over again. The spec says that `Dispose()` must be able to be called any number of times. – Andrew Barber Mar 03 '13 at 06:42