我需要调用ServiceController的Close()方法吗?

4

我有一个现有的方法如下:

    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;
        }
    }

这是使用ServiceController类的正确方式吗?

我问这个问题的原因是,我看到的所有示例在使用完后都没有调用Close()方法。这些示例是错误的还是我漏掉了什么?

4个回答

7
您正在使用带有using语句的ServiceController。这将调用Dispose,这与显式调用Close()相同。
因此,在您的情况下,没有必要再次调用Close()。
如果没有使用using语句,则需要在ServiceController上调用Close()或Dispose(),因为它使用需要释放的非托管资源。否则会导致内存泄漏。
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();
  }
}

4

您的示例将 ServiceController 包装在 using 语句中,这将调用 Dispose 方法来清理对象。这相当于调用 Close 方法。


4

Close()没有被调用,因为这里使用了using语法糖。

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

等同于:

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

自动调用Dispose()清理资源。
更多信息请参见此博客

0

我一遍遍地使用了 close() 方法,但我无法再次使用 dispose()。Dispose() 使用了数据库连接...


1
我不知道为什么有两个人点赞了这个。最后一句话没有意义,而第一句话是错误的。您可以重复地调用Dispose()多次。规范说明Dispose()必须能够被任意次数地调用。 - Andrew Barber

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接