我应该在ServiceController上调用Close()吗? [英] Should I call Close() on ServiceController?
问题描述
目前,我有这样一种方法:
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屋!