我应该在ServiceController上调用Close()吗? [英] Should I call Close() on ServiceController?

查看:53
本文介绍了我应该在ServiceController上调用Close()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有这样一种方法:

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

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

Is this the right way to use the ServiceController class?

我问的原因是,我看过的所有示例在使用完它们后都不会调用 Close()方法.是那些不好的例子还是我错过了什么?

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?

推荐答案

您正在将 ServiceController using 语句一起使用.这将在ServiceController上调用 Dispose ,与显式调用Close()相同.

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.

在没有使用状态的情况下,有必要在ServiceController上调用Close()或Dispose(),因为它使用了需要释放的非托管资源.否则会发生内存泄漏.

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

这篇关于我应该在ServiceController上调用Close()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆